The call(), apply(), and bind() methods allow you to change the runtime binding of a function’s this
keyword from the function’s lexical object to a different object of your choice.
All three of the call
, bind
, and apply
methods set the this
argument to the function.
- The
call
andapply
methods setthis
to a function and call the function. - The
bind
method will only setthis
to a function. We will need to separately invoke the function.
call
The call
method binds the this
value to the function and executes the function. It takes the this
value and a list of arguments as parameters. Then, it returns the value returned by the function, which is called using the call
method.
function test(arg1, arg2){
console.log(this.num, arg1, arg2); // 100, 10, 20
}
test.call({num: 100}, 10, 20);
In the code above, we have called the test
function using the call
method. The call
method will invoke the test
function with the this
value as the object passed to the call
method.
apply
The apply
method binds the this
value to the function and executes the function. It takes the this
value and a single array object as parameters, and it returns the value returned by the function, which is called using the apply
method.
function test(...arguments){
console.log(this.num, arguments);//100, [1,2,3]
}
test.apply({num: 100}, [1,2,3]);
In the code above, we have called the test
function using the apply
method and with the this
value as the object passed to the apply
method.
call()
andapply()
are identical in functionality, the only difference is thatcall()
accepts a list of arguments; whereas,apply()
accepts a single array of arguments.
bind
The bind
method binds the this
value to the function and returns a new function. However, we still need to separately invoke the returned function.
function test(arg){
console.log(this.number, arg);
}
let bindedFn = test.bind({number: 99}, "argument");
bindedFn(); // 99, "argument"
In the above code, we bind the this
value for the test
function and invoke the returned function from the bind
method.
Summary
call
: binds thethis
value, invokes the function, and allows you to pass a list of arguments.apply
: binds thethis
value, invokes the function, and allows you to pass arguments as an array.bind
: binds thethis
value, returns a new function, and allows you to pass in a list of arguments.