The bind() method allows an object to borrow a method from another object.
The example below creates two objects (person and member), where the member object borrows the fullName method from the person object.
const person = { firstName:“John”, lastName: “Doe”, fullName: function () { return this.firstName + ” “ + this.lastName; } } const member = { firstName:“Hege”, lastName: “Nilsen”, } let fullName = person.fullName.bind(member); |
The bind() method is sometimes necessary to prevent losing the correct this context.
In the following example, the person object has a display method, and within this method, this refers to the person object.
const person = { firstName:“John”, lastName: “Doe”, display: function () { let x = document.getElementById(“demo”); x.innerHTML = this.firstName + ” “ + this.lastName; } } person.display(); |
When a function is used as a callback, the this context is lost.
In this example, the intention is to display the person’s name after 3 seconds, but it will display undefined instead.
const person = { firstName:“John”, lastName: “Doe”, display: function () { let x = document.getElementById(“demo”); x.innerHTML = this.firstName + ” “ + this.lastName; } } setTimeout(person.display, 3000); |
The bind() method resolves this issue.
In the following example, bind() is used to bind person.display to the person object.
This ensures that the person’s name is displayed after 3 seconds.
const person = { firstName:“John”, lastName: “Doe”, display: function () { let x = document.getElementById(“demo”); x.innerHTML = this.firstName + ” “ + this.lastName; } } let display = person.display.bind(person); setTimeout(display, 3000); |
In JavaScript, the this keyword refers to an object, but the object it refers to can vary depending on how this is used.
In an object method, |
When used alone, |
In a function, this refers to the global object. |
In a function, when in strict mode, this is undefined. |
In an event handler, this refers to the element that triggered the event. |
Methods like call(), apply(), and bind() allow you to set this to any object. |
Note: this is a keyword, not a variable, and its value cannot be changed. |