bind()
- With bind method, an object can borrow a method from another object.
-
object1.method1
object1.method1.bind(object2)
- Getting the function and return value:
-
object1.method1()
const method2 = object1.method1.bind(object2);
method2
method2()
call()
vs bind()
-
object1.method1
object1.method1()
object1.method1.call(object2)
object1.method1.bind(object2)
let method2 = object1.method1.bind(object2);
method2
method2()
- Similarities:
- Allowing a method of an object to be used with a different object
- Differences:
call
: Calling a method to be executed. Result: the return value and other consequences of the code being executed.
bind
: Creating a new method, but not to execute. Result: a new function.
bind()
example
-
const person1 = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName: "Michael",
lastName: "Scott",
}
let fullName2 = person1.fullName.bind(person2);
person1.fullName();
fullName2();