返回
将this锁定的三种方法:call、apply、bind
前端
2023-11-08 23:14:22
前言
在JavaScript中,this
代表着函数执行时内部的当前对象。this
的动态绑定为JavaScript创造了巨大的灵活性,但也带来了麻烦。有时,需要把this
固定下来,避免出现意想不到的情况。JavaScript提供了call
、apply
、bind
这三个方法,可以用来绑定this
。
call和apply
call
和apply
方法的作用是立即执行一个函数,并指定this
指向的对象。这两个方法的区别在于参数传递的方式。call
方法的参数列表中第一个参数是this
要绑定的对象,后面的参数是函数的参数列表,而apply
方法的参数列表中第一个参数是this
要绑定的对象,第二个参数是函数的参数列表,是一个数组。
// call示例
function greet(name) {
console.log(`Hello, ${name}!`);
}
const person = {
name: 'John Doe'
};
greet.call(person, 'Jane Doe'); // 输出:Hello, Jane Doe!
// apply示例
function sum(a, b) {
return a + b;
}
const numbers = [1, 2, 3, 4, 5];
sum.apply(null, numbers); // 输出:15
bind
bind
方法的作用是创建一个新的函数,这个新函数的this
绑定到指定的对象。与call
和apply
方法不同,bind
方法不会立即执行函数,而是返回一个新的函数。
function greet(name) {
console.log(`Hello, ${name}!`);
}
const person = {
name: 'John Doe'
};
const boundGreet = greet.bind(person);
boundGreet('Jane Doe'); // 输出:Hello, Jane Doe!
比较
方法 | 参数 | 返回值 |
---|---|---|
call |
thisArg , arg1 , arg2 , ... |
undefined |
apply |
thisArg , [arg1, arg2, ...] |
undefined |
bind |
thisArg , arg1 , arg2 , ... |
新函数 |
总结
call
、apply
和bind
这三个方法都可以用来绑定this
,但它们在使用方式和返回值上有所不同。call
和apply
方法立即执行函数,而bind
方法返回一个新的函数。call
方法的参数列表中第一个参数是this
要绑定的对象,后面的参数是函数的参数列表,apply
方法的参数列表中第一个参数是this
要绑定的对象,第二个参数是函数的参数列表,是一个数组,bind
方法的参数列表中第一个参数是this
要绑定的对象,后面的参数是函数的参数列表。