It’s not magic: using bind() in javascript

Maybe you’ve used bind before, and yeah, it works. But why? Dumb people like me don’t always fully understand why we do stuff. When we finally find our solution, after hours of searching and feeling disgusted by our own stupidity, we just don’t have the energy to find out why this stuff works.

Well, it’s actually quite easy, but it has everything to do with the keyword this. I found a great reference on javascriptissexy.com:

“First, know that all functions in JavaScript have properties, just as objects have properties. And when a function executes, it gets the this property — a variable with the value of the object that invokes the function where this is used.”

Example time:

var Person = {
name: 'Sam',
sayName: function(){
console.log('My name is '+ this.name);
}
};
Person.sayName(); // 'My name is Sam'

Lets compare our reference from javascriptissexy.com to our piece of code: We’ve executed our function sayName(). Because we executed a function that’s originating from our Person object, the sayName() function received the property this.

That property (this) is a variable, which refers to Person. Why? Because it was the object Person that invoked the function sayName().

Bring the bind, bruh

Let’s run another example. This time we use the same example, but with an addEventListener:

var Person = {
name: 'Sam',
sayName: function(){
console.log('My name is '+ this.name);
}
};
document
.getElementById('test')
.addEventListener('click', Person.sayName);

I’ve omitted the html. But if you don’t know what this is trying to do: it executes the sayName function when the user clicks on a button with id=”test”.

But this shit is broken. It don’t work. Why? First: HTML nodes are Objects. So when we write:

document.getElementById('test);

we refer to a button Object.

addEventListener is a method that’s attached to our button Object. That means, that the Object that invokes the function isn’t Person anymore. The Object that invokes the function is the button.

That means that this now refers to our button. So when we use this in Person.sayName(), it will not refer to Person, but to our button. And our button does not have a name property. So it will result in an ‘undefined’.

Finally, here comes the bind

Here is where bind comes into play. With bind, you can literally bind this to your desired Object:

var Person = {
name: 'Sam',
sayName: function(){
console.log('My name is '+ this.name);
}
};
document
.getElementById('test')
.addEventListener('click', Person.sayName.bind(Person));
// 'My name is Sam'

Now, thanks to bind, this, that we use in the sayName() function, refers to Person again. And our console log prints the correct text again.

And there you go. It’s not magic. Just javascript.

One clap, two clap, three clap, forty?

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