「JavaScript」回顾bind()、apply()和 call()

发布于 2023-06-08  61 次阅读


bind(), apply(), 和 call() 都是 JavaScript 中用于管理函数执行上下文的方法。它们允许你显式地指定函数执行时的 this 值,并且可以传递参数给函数。下面我会详细解释这三个方法并举例说明它们的用法。

bind()

bind() 方法创建一个新的函数(注意是返回一个新的函数,而不会立即调用被绑定的函数),当这个新函数被调用时,它的 this 值会被指定为传递给 bind() 方法的第一个参数。而后续的参数将作为新函数调用时的参数传递进去。

const person = {
    name: 'John',
    greet: function() {
        console.log(`Hello, ${this.name}!`);
    }
};

const greetFunc = person.greet.bind(person); // 将 person.greet 函数绑定到 person 对象上
const testFunc = person.greet; // 未绑定this, this是 Object [global] 全局对象

greetFunc(); // 输出: Hello, John!
testFunc(); // 输出: Hello, undefined!

在上面的例子中,bind() 方法将 person.greet 函数绑定到 person 对象上,并将 greetFunc 变量指向新的函数。当调用 greetFunc() 时,this 的值将被设置为 person 对象,因此输出为 "Hello, John!"。

bind()还可以给绑定的函数预定前几个参数,被预定的参数被展开从第二个参数上开始写。如func.bind(object, param1, param2, param3)。示例如下:

"use strict"; // prevent `this` from being boxed into the wrapper object

function log(...args) {
  console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6

apply()

apply() 方法调用一个函数(立即调用被绑定的函数,而不是返回一个新的函数),并将指定的 this 值和参数作为数组(或类似数组的对象)传递给函数。

function greet(message) {
    console.log(`${message}, ${this.name}!`);
}

const person = {
    name: 'John'
};

greet.apply(person, ['Hello']); // 输出: Hello, John!

在上面的例子中,apply() 方法将 person 对象作为 greet 函数执行时的 this 值,并将 ['Hello'] 数组作为参数传递给函数。因此输出为 "Hello, John!"。

call()

call() 方法与 apply() 方法类似,但是参数需要逐个传递而不是作为数组。

function greet(message) {
    console.log(`${message}, ${this.name}!`);
}

const person = {
    name: 'John'
};

greet.call(person, 'Hello'); // 输出: Hello, John!

在上面的例子中,call() 方法将 person 对象作为 greet 函数执行时的 this 值,并将 'Hello' 作为参数传递给函数。因此输出为 "Hello, John!"。

这些方法可以帮助你控制函数执行时的上下文和参数传递,非常有用。它们经常在事件处理程序、回调函数以及需要控制函数上下文的其他情况下使用。


A Student on the way to full stack of Web3.