返回

JS中的this五种绑定机制详解

前端

对于一个初学者而言,JS 中的 this 机制可能有点复杂难懂。但是,一旦你掌握了它的工作原理,你就可以更自信地编写出健壮、可维护的代码。

本文将深入探究 JS 中 this 的五个关键绑定机制:

绑定机制

this 的值根据函数的调用方式而定。有五种不同的机制可以绑定 this:

  • 默认绑定
  • 隐式绑定
  • 显式绑定
  • new 绑定
  • 箭头函数绑定

1. 默认绑定

当函数作为对象方法调用时,this 被绑定到该对象。

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

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

2. 隐式绑定

当函数作为非对象方法调用时,this 被绑定到全局对象(在浏览器中为 window,在 Node.js 中为 global)。

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

greet(); // 输出:"Hello, undefined!"

3. 显式绑定

使用 call() 或 apply() 方法可以显式地绑定 this。call() 接受单个 this 参数,而 apply() 接受一个数组作为 this 参数。

const person = {
  name: "John",
};

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

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

4. new 绑定

当函数用 new 运算符调用时,this 被绑定到新创建的对象。

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

const person = new Person("John");
console.log(person.name); // 输出:"John"

5. 箭头函数绑定

箭头函数没有自己的 this 绑定。它们继承了包含它们的词法作用域中的 this 绑定。

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

person.greet(); // 输出:"Hello, undefined!"