JavaScript Function bind()


Function Borrowing

The bind() method allows an object to use a method from another object.

The sample code below generates two objects, namely "person" and "member."

The member object uses the fullname method from the person object.


Preserving this

At times, you may need to use the bind() method to avoid losing the reference to this.

In this example, there's a person object with a display method. Within the display method, the keyword this pertains to the person object:

When a function is employed as a callback, the reference to this is no longer retained.

This example attempts to show the person's name after a delay of 3 seconds. However, it ends up showing undefined instead.

The issue is resolved by using the bind() method.

In this example, the bind() method is employed to connect the function person.display with the object person.

This illustration will show the name of a person after a delay of 3 seconds.


What is this?

In JavaScript, when we use the this keyword, it points to an object.

Which object's dependence relies on how the this is used or called.

The word "this" points to various things based on how it's employed:

In a method related to an object, the term this points to the object.
By itself, the term this points to the global object.
In a function, the keyword thispoints to the global object.
In a function under strict mode, the value of this is undefined.
At an event, the term this points to the specific element that experienced the event.
The call(), apply(), and bind() methods enable the reference of this to be associated with any object.

Note

this isn't a variable; it's a keyword. You can't modify the value of this.

See Also:

The JavaScript this Tutorial