JS: bind()

I’ve read somewhere that every cool JS developer should now answers to 3 questions: what is (and how it works) bind(), closures and promises. Of course it was just someone’s personal opinion but can you answer those questions?

So in this post lets talk about bind()

From the MDN docs:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

It other words, bind() allows us to easily set which specific object will be bound to this when a function or method is invoked.

This might seem relatively trivial, but often the this value in methods and functions must be set explicitly when you need a specific object bound to the function’s this value.

Well, let’s take a function that looks like this :

var logProp = function(prop) {
console.log(this[prop]);
};

Now, let’s take an object that looks like this :

var Obj = {
x : 5,
y : 10
};

We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, we can run Obj.log anywhere in our code :

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of this to our object Obj.

Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

Bind () Allows us to Borrow Methods

In JavaScript, we can pass functions around, return them, borrow them, and the like. And the bind() method makes it super easy to borrow methods.

Here is an example using bind() to borrow a method. Lets say we have this method

var user = {
// local data variable​
data:[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}

// Assign the showData method of the user object to a variable​
var showDataVar = user.showData.bind(user);

// Now the we get the value from the user object because the this keyword is bound to the user object​
showDataVar(); // P. Mickelson 43​

Lets borrow method:

var cars = {
data:[
{name:"Honda Accord", age:14},
{name:"Tesla Model S", age:2}
]
}

// We can borrow the showData () method from the user object we defined above.​
// Here we bind the user.showData method to the cars object we just created.​
 cars.showData = user.showData.bind (cars);
cars.showData (); // Honda Accord 14​

One problem with this example is that we are adding a new method (showData) on the cars object and we might not want to do that just to borrow a method because the cars object might already have a property or method name showData. We don’t want to overwrite it accidentally. As i read somewhere in this case better to use Apply and Call methods which i will explore another time.

JavaScript’s Bind Allows Us to Curry a Function

Let’s use the bind()method for currying. First we have a simple greet () function that accepts 3 parameters:

function greet (gender, age, name) {
// if a male, use Mr., else use Ms.​
var salutation = gender === "male" ? "Mr. " : "Ms. ";

if (age > 25) {
return "Hello, " + salutation + name + ".";
}
else {
return "Hey, " + name + ".";
}
}

And we use the bind() method to curry (preset one or more of the parameters) our greet() function. The first argument of the bind() method sets the this value, as we discussed earlier:

var greetAnAdultMale = greet.bind (null, "male", 45);

greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."​

var greetAYoungster = greet.bind (null, "", 16);
greetAYoungster ("Alex"); // "Hey, Alex."​
greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."​

When we use the bind() method for currying, all the parameters of the greet() function, except the last (rightmost) argument, are preset. So it is the rightmost argument that we are changing when we call the new functions that were curried from the greet() function.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.