返回

告别困扰!轻松掌控 JavaScript 中的 this、call、apply 与 bind

前端

在 JavaScript 的世界中,this 经常扮演令人困惑的角色。它是一个难以捉摸的家伙,其值可能会根据不同的情况而变化。这常常让开发者们感到头疼不已。

为了拨开 this 关键字的重重迷雾,我将通过四条清晰的规则,带你领略它的真面目。我们还将探索 call、apply 和 bind 这三个强大函数,以便你在 JavaScript 代码中轻松操控 this。

规则一:隐式绑定 - 由谁调用,this 就属于谁

隐式绑定是最常见的绑定方式,当函数被直接调用时,this 就隐式地绑定到调用该函数的对象。

例如,我们有一个名为 person 的对象,该对象具有一个名为 sayName 的方法:

const person = {
  name: 'John Doe',
  sayName: function() {
    console.log(this.name);
  }
};

person.sayName(); // 输出: John Doe

在此示例中,person.sayName() 被直接调用,因此 this 被隐式地绑定到 person 对象。

规则二:显式绑定 - 主动指定 this 的指向

显式绑定允许我们手动指定 this 的指向,以便在不同的上下文中使用同一个函数。

我们仍然使用 person 对象作为示例,这次我们使用 .call() 和 .apply() 方法来显式绑定 this:

// 使用 .call() 显式绑定 this
person.sayName.call({ name: 'Jane Doe' }); // 输出: Jane Doe

// 使用 .apply() 显式绑定 this
person.sayName.apply({ name: 'John Smith' }); // 输出: John Smith

在上述示例中,我们使用 .call() 和 .apply() 方法将 this 显式绑定到不同的对象。.call() 接受一个参数作为 this 的值,而 .apply() 接受一个数组作为 this 的值。

规则三:new 绑定 - 创建新对象并自动绑定 this

new 绑定用于创建新对象并自动将 this 绑定到该新对象。

例如,我们创建一个 Person 构造函数:

function Person(name) {
  this.name = name;
}

const john = new Person('John Doe');
console.log(john.name); // 输出: John Doe

在上述示例中,new Person('John Doe') 语句创建了一个新的 Person 对象,并将 this 自动绑定到该对象。

规则四:window 绑定 - 全局作用域中的 this

当函数在全局作用域中调用时,this 被绑定到 window 对象。

例如,在浏览器中,我们可以在控制台中输入以下代码:

console.log(this); // 输出: Window

这将输出 window 对象。

理解了这四条规则,你就能轻松掌控 JavaScript 中的 this 关键字,灵活运用 .call、.apply 和 .bind 方法,在不同的上下文中使用相同的函数,创建新对象并自动绑定 this,以及在全局作用域中使用 this。

JavaScript 中的 this 关键字就像一个善变的精灵,但只要掌握了它的规则,你就能驾驭它,写出更清晰、更易维护的代码。