Skip to content

Instantly share code, notes, and snippets.

@cihat
Created November 16, 2020 10:34
Show Gist options
  • Save cihat/9a7f07ad35ad238ba67a113ddd290131 to your computer and use it in GitHub Desktop.
Save cihat/9a7f07ad35ad238ba67a113ddd290131 to your computer and use it in GitHub Desktop.
The bind() Method
The third function method for changing this is bind(). This method was
added in ECMAScript 5, and it behaves quite differently than the other
two. The first argument to bind() is the this value for the new function.
All other arguments represent named parameters that should be permanently set in the new function. You can still pass in any parameters that
aren’t permanently set later.
The following code shows two examples that use bind(). You create
the sayNameForPerson1() function by binding the this value to person1, while
sayNameForPerson2() binds this to person2 and binds the first parameter as
"person2".
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var person1 = {
name: "Nicholas"
};
var person2 = {
name: "Greg"
};
// create a function just for person1
u var sayNameForPerson1 = sayNameForAll.bind(person1);
sayNameForPerson1("person1"); // outputs "person1:Nicholas"
// create a function just for person2
v var sayNameForPerson2 = sayNameForAll.bind(person2, "person2");
sayNameForPerson2(); // outputs "person2:Greg"
// attaching a method to an object doesn't change 'this'
w person2.sayName = sayNameForPerson1;
person2.sayName("person2"); // outputs "person2:Nicholas"
No parameters are bound for sayNameForPerson1() u, so you still need
to pass in the label for the output. The function sayNameForPerson2() not
only binds this to person2 but also binds the first parameter as "person2" v.
That means you can call sayNameForPerson2() without passing in any additional arguments. The last part of this example adds sayNameForPerson1()
onto person2 with the name sayName w. The function is bound, so the value
of this doesn’t change even though sayNameForPerson1 is now a function on
person2. The method still outputs the value of person1.name.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment