返回

this 究竟是什么?

前端

引言

this 是 JavaScript 中一个独特而强大的概念。它使我们能够访问和操作当前执行上下文中的对象。理解 this 的行为对于编写健壮且可维护的 JavaScript 代码至关重要。本文将深入探讨 this 的世界,揭开它的奥秘,并为您提供一个清晰的理解。

this 的本质

简单来说,this 代表当前执行上下文中的对象。它是一个动态值,根据代码执行时的上下文而改变。在大多数情况下,this 隐含地指向调用该方法或函数的对象。

隐式传递

隐式传递是最常见的 this 传递方式。当一个方法或函数被一个对象调用时,this 隐含地指向该对象。例如:

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

person.sayName(); // "John Doe"

在这个例子中,sayName() 方法隐含地接收 this 作为 person 对象,因为它是由 person 对象调用的。

显示传递

在某些情况下,我们可能需要显式地传递 this。这可以通过 call()、apply() 或 bind() 方法实现。这些方法允许我们指定 this 的值,即使它不是隐含传递的。

例如:

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

function sayName() {
  console.log(this.name);
}

sayName.call(person); // "John Doe"

在这个例子中,我们使用 call() 方法显式地将 this 设置为 person 对象,即使 sayName() 方法不是由 person 对象调用的。

this 的常见考题

为了加深对 this 的理解,让我们看一下一些常见的考题:

例题一: 下面的函数调用中,this 分别是什么?

function sayName() {
  console.log(this.name);
}

// 方法:把所有的函数调用改为 call 的写法
sayName(); // undefined
sayName.call(person); // "John Doe"
sayName.apply(person); // "John Doe"

答案:

  • sayName():undefined(隐式传递,指向全局对象)
  • sayName.call(person):"John Doe"(显式传递 this 为 person)
  • sayName.apply(person):"John Doe"(显式传递 this 为 person)

例题二: 下面的代码中,this 是什么?

const object = {
  name: "John Doe",
  sayName: function() {
    const innerFunction = function() {
      console.log(this.name);
    };

    innerFunction(); // undefined
  }
};

object.sayName(); // "John Doe"

答案:

  • object.sayName():"John Doe"(隐式传递 this 为 object)
  • innerFunction():undefined(隐式传递 this 为全局对象)

结论

this 关键字是 JavaScript 中一个基础性的概念。通过了解它的隐式和显示传递机制,我们能够编写出更加清晰和健壮的代码。掌握 this 的用法不仅可以提升代码质量,还可以帮助我们更好地理解 JavaScript 面向对象编程的思想。