Using JavaScript's bind() function
Since it was introduced in 2009’s ECMAScript 5 (ES5) specification, all functions have the bind()
method. Using it creates a new function that calls the original with some arguments already fixed. This is known as a "partial function application".
Using bind
to set parameters
Partially applying a function using bind()
allows us to fill in arguments before the function is called. In the following example, bind()
is used to create a new function that takes add()
, but only requires a single parameter: x
is always going to be 1:
function add(x, y) {
return x + y;
}
var plus1 = add.bind(null, 1);
console.log(plus1(5)); // 6
Using bind
to set this
bind()
can also be used to allow the developer to specify the context in which this
must be used. In the example above, we passed null
. In the next, we don’t pass any additional arguments, but provide the function an object. As we learnt previously, this
is bound explicitly when set this way.
function foo(something) {
console.log(this.a, something);
return this.a + something;
}
var obj = {
a: 2,
};
var bar = foo.bind(obj);
var b = bar(3); // 2 3
console.log(b); // 5