js 中的 this、call、apply 与 bind
2023-09-18 11:26:50
在 JavaScript 中,this
是一个非常重要的概念,它表示当前执行代码的上下文对象。this
的值可以在函数内部、对象方法中或事件处理程序中发生变化。
call()
、apply()
和 bind()
是 JavaScript 中内置的函数,它们允许我们显式地设置函数的 this
值。这在需要在不同对象上下文中调用函数时非常有用。
call()
方法
call()
方法接受两个参数:第一个参数是 this
的值,第二个参数及以后的参数是传递给函数的参数。call()
方法直接调用函数,并立即执行它。
例如,我们有一个 person
对象,它有一个 greet()
方法。我们想在另一个对象 context
的上下文中调用 greet()
方法。我们可以使用 call()
方法来实现:
const person = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const context = {
name: 'Jane'
};
person.greet.call(context); // 输出: Hello, my name is Jane.
apply()
方法
apply()
方法与 call()
方法类似,但它接受一个数组作为第二个参数,该数组包含传递给函数的参数。apply()
方法也直接调用函数,并立即执行它。
例如,我们想使用 Math.max()
函数来查找一组数字中的最大值。我们可以使用 apply()
方法来实现:
const numbers = [1, 2, 3, 4, 5];
const max = Math.max.apply(null, numbers); // 输出: 5
bind()
方法
bind()
方法与 call()
和 apply()
方法不同,它不立即调用函数,而是返回一个新的函数,该函数的 this
值已绑定到指定的 this
值。当我们调用这个新的函数时,this
的值将是绑定的值,而传递给 bind()
方法的任何参数都将作为参数传递给新的函数。
例如,我们想创建一个新的函数,该函数将 person.greet()
方法绑定到 context
对象。我们可以使用 bind()
方法来实现:
const person = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const context = {
name: 'Jane'
};
const boundGreet = person.greet.bind(context);
boundGreet(); // 输出: Hello, my name is Jane.
比较
下表比较了 call()
、apply()
和 bind()
方法:
方法 | 语法 | 参数 | 返回值 |
---|---|---|---|
call() |
func.call(thisValue, arg1, arg2, ...) |
thisValue 和传递给函数的参数 |
undefined |
apply() |
func.apply(thisValue, [args]) |
thisValue 和一个包含传递给函数的参数的数组 |
undefined |
bind() |
func.bind(thisValue, arg1, arg2, ...) |
thisValue 和传递给 bind() 方法的参数 |
一个新的函数,其 this 值已绑定到指定的 this 值 |
总结
call()
、apply()
和 bind()
方法都是 JavaScript 中非常有用的工具,它们允许我们显式地设置函数的 this
值。这在需要在不同对象上下文中调用函数时非常有用。