call
, apply
and bind
are all methods used to explicitly modify this
the value of a function. The differences between them are as follows:
call
method:call
The method immediately calls the function, passing the specified object as the function'sthis
value.call
The method accepts a list of parameters, which are passed to the function in turn.- If the function needs to pass multiple parameters, you can use commas to separate the parameters passed to
call
the method. call
The syntax of the method is:function.call(thisArg, arg1, arg2, ...)
function sayHello(greeting) {
console.log(greeting + ', ' + this.name);
}
const obj = {
name: 'Alice'
};
sayHello.call(obj, 'Hello'); // 输出:Hello, Alice
apply
method:apply
The method immediately calls the function, passing the specified object as the function'sthis
value.apply
The method accepts two parameters:thisArg
and a parameter array.- The elements in the parameter array are passed to the function in sequence.
- If the function needs to pass multiple parameters, and these parameters already exist in the array, you can use
apply
the method. apply
The syntax of the method is:function.apply(thisArg, [argsArray])
function sayHello(greeting) {
console.log(greeting + ', ' + this.name);
}
const obj = {
name: 'Alice'
};
sayHello.apply(obj, ['Hello']); // 输出:Hello, Alice
bind
method:bind
The method creates a new function, binds the specified object to the function'sthis
value, and returns the new function.- The bound
this
value does not immediately execute the function, but instead returns a new function that can be called when needed. bind
Methods can pass additional parameters as parameters to the bound function.bind
The syntax of the method is:function.bind(thisArg, arg1, arg2, ...)
function sayHello() {
console.log(this.name);
}
const obj = {
name: 'Alice'
};
const boundFunc = sayHello.bind(obj);
boundFunc(); // 输出:Alice
Summarize:
call
The andapply
methods are used to call a function immediately, passing the specifiedthis
value and parameter list.bind
Method is used to create a new function andthis
bind the specified value to the function.call
Methods take a comma separated list of arguments,apply
methods take an array of arguments, andbind
methods can pass arguments when creating a new function.call
The andapply
methods will execute the function immediately, whilebind
the method returns a new function that needs to be called manually.- All of these methods allow the function's value to be modified explicitly
this
so that the function executes correctly in a specific context. The method chosen depends on whether the function needs to be executed immediately and how the parameters are passed.