Function Borrowing
With the bind() method, an object can borrow a method from another object.
The example below creates two objects, teacher and student. The student object borrows the getFullName method from the teacher object:
Example:
const teacher = { firstName: "Alice", lastName: "Johnson", getFullName: function () { return this.firstName + " " + this.lastName; } }; const student = { firstName: "Bob", lastName: "Smith", }; let fullName = teacher.getFullName.bind(student);
Preserving this
Sometimes the bind() method has to be used to prevent losing the context of this.
In the following example, the user object has a showName method. Within the showName method, this refers to the user object:
Example:
const user = { firstName: "Charlie", lastName: "Brown", showName: function () { let element = document.getElementById("output"); element.innerHTML = this.firstName + " " + this.lastName; } }; user.showName();
When a function is used as a callback, the context of this is lost. This example will try to display the user's name after 3 seconds, but it will display undefined instead:
Example:
const user = { firstName: "Charlie", lastName: "Brown", showName: function () { let element = document.getElementById("output"); element.innerHTML = this.firstName + " " + this.lastName; } }; setTimeout(user.showName, 3000);
The bind() method solves this problem. In the following example, the bind() method is used to bind user.showName to user. This example will display the user's name after 3 seconds:
Example:
const user = { firstName: "Charlie", lastName: "Brown", showName: function () { let element = document.getElementById("output"); element.innerHTML = this.firstName + " " + this.lastName; } }; let showName = user.showName.bind(user); setTimeout(showName, 3000);