返回

JS 中的 This:揭开神秘面纱

前端

前言

在 JavaScript 中,this 是一个特殊的,它指向当前执行代码的对象。它在函数中非常有用,可以让你访问函数所属的对象的属性和方法。例如,在一个对象的方法中,this 指向该对象本身。在全局作用域中,this 指向全局对象,通常是 window 对象。

This 的工作原理

this 的值由函数的调用方式决定。有两种主要的方式来调用函数:

  • 显式绑定: 当你使用 dot(.)或 bracket([])运算符调用一个函数时,this 被显式绑定到调用它的对象。例如:
const person = {
  name: 'John Doe',
  greet: function() {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.greet(); // Output: Hello, my name is John Doe!

在这个例子中,this 被显式绑定到 person 对象,因为 greet() 方法是在 person 对象上调用的。因此,this.name 等同于 person.name。

  • 隐式绑定: 当你使用 function() 或箭头函数(=>)调用一个函数时,this 被隐式绑定到全局对象。例如:
function greet() {
  console.log(`Hello, my name is ${this.name}!`);
}

greet(); // Output: Hello, my name is undefined!

在这个例子中,this 被隐式绑定到全局对象,因为 greet() 函数是在全局作用域中调用的。因此,this.name 等同于 window.name,而 window.name 通常是 undefined。

严格模式下的 This

在严格模式下,this 的行为略有不同。在严格模式下,直接调用函数,this 不会被绑定到 window 对象上,而是被绑定到 undefined 上。例如:

"use strict";

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

greet(); // Output: TypeError: Cannot read property 'name' of undefined

在这个例子中,由于 greet() 函数是在严格模式下定义的,this 被绑定到 undefined 上。因此,this.name 等同于 undefined.name,而 undefined.name 是一个不存在的属性,因此会抛出一个错误。

箭头函数中的 This

箭头函数(=>)是一种新的函数语法,它没有自己的 this。箭头函数中的 this 与它周围的代码块中的 this 相同。例如:

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

person.greet(); // Output: Hello, my name is John Doe!

在这个例子中,greet() 方法是一个箭头函数,它没有自己的 this。因此,this 与它周围的代码块中的 this 相同,即 person 对象。因此,this.name 等同于 person.name。

总结

this 是一个非常重要的 JavaScript 概念,它决定了函数内部的 this 关键字所指向的对象。this 的值由函数的调用方式决定。显式绑定时,this 被绑定到调用它的对象。隐式绑定时,this 被绑定到全局对象。在严格模式下,直接调用函数,this 不会被绑定到 window 对象上,而是被绑定到 undefined 上。箭头函数没有自己的 this,this 与它周围的代码块中的 this 相同。