A short explanation of bind and .this in JavaScript

Introduction

We've noticed that many people which start to learn JavaScript are having difficulties when they try to understand certain concepts.

Understanding how .this works it is one of these concepts.

This is usually explained better in conjunction with bind function.

JavaScript bind and .this in a simple way

One way to explain this and to gain a full understanding is to use a funny example like below.

I think this will be really easy to understand.

Let's say that I have an orange (yes, an orange, the one you eat and smells great).

Then you have a grape (yes, the grape used to make wine) which is inside a basket.

For a better understanding, we can also say that the orange it's in a bigger basket and the basket with the grape it's inside the big basket.

Like in the below image:

this bind JS explain

Let's put this into JavaScript:

var myFruit = "orange";

var myBasket = {

myFruit: "grape",
getMyFruit: function () {
return this.myFruit;
}
};

myBasket.getMyFruit(); // "grape"

var getMyFruit = myBasket.getMyFruit;
getMyFruit(); // "orange", because in this case, "this" refers to the global object

var bindGetMyFruit = getMyFruit.bind(myBasket);
bindGetMyFruit(); // "grape"

We can think to the big basket as being the DOM (Document Object Model).

When we use the first function myBasket.getMyFruit(), in this case .this refers to myBasket object and the result will be "grape".

When we use the second function getMyFruit(), .this will refer to the big basket (DOM) and therefore the result is "orange" because we have the orange in the big basket.

If we want to have "grape" as a result, then we need to use the bind function: var bindGetMyFruit = getMyFruit.bind(myBasket).

I hope you will find this explanation useful. Please let me know what you think.

Comments closed

Please contact me, if you have any questions or suggestions.