深入理解 JS —— this 关键词

this 是一个指向当前执行上下文的对象的引用。在不同的上下文中,this 的值可以有所不同。

常见用法

全局上下文中的 this

在全局执行上下文中(不在函数内),this 指向全局对象。在浏览器环境中,全局对象是 window,在 Node.js 中是 global

1
console.log(this);  // 浏览器中输出:window

函数调用中的 this

在普通函数调用中,this 依赖于调用该函数的方式。

1
2
3
4
5
function showThis() {
  console.log(this);
}

showThis();  // 在浏览器中,输出:window(全局对象)

函数中的 this 默认指向全局对象(在严格模式下为 undefined)。但是,this 的值会根据调用方式发生变化。

方法调用中的 this

当函数作为对象的方法调用时,this 会指向调用该方法的对象。

1
2
3
4
5
6
7
8
const person = {
  name: 'Alice',
  greet: function() {
    console.log(this.name);
  }
};

person.greet();  // 输出:Alice

在这个例子中,greetperson 对象的方法,this 指向 person 对象,因此 this.name 访问了 personname 属性。

构造函数中的 this

在构造函数中,this 指向新创建的实例对象。通过 new 关键字调用构造函数时,this 会指向新创建的对象。

1
2
3
4
5
6
function Person(name) {
  this.name = name;
}

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

在这个例子中,Person 是一个构造函数,this 指向新创建的 john 对象。

箭头函数中的 this

箭头函数与普通函数不同,箭头函数没有自己的 this,它会继承外部作用域的 this 值。也就是说,箭头函数中的 this 指向定义时的 this,而不是调用时的 this

1
2
3
4
5
6
7
8
9
10
11
const person = {
  name: 'Alice',
  greet: function() {
    const arrowFunc = () => {
      console.log(this.name);
    };
    arrowFunc();
  }
};

person.greet();  // 输出:Alice

在这个例子中,arrowFunc 是一个箭头函数,它继承了 greet 方法的 this,因此它指向 person 对象。

callapplybind 改变 this

callapplybind 方法可以显式地改变 this 的指向。

  • callapply 立即调用函数,但传递给 this 的对象不同。
  • bind 返回一个新的函数,但不会立即执行,而是将 this 永久绑定到指定的对象。
1
2
3
4
5
6
7
8
9
10
11
function greet() {
  console.log(this.name);
}

const person = { name: 'Alice' };

greet.call(person);  // 输出:Alice
greet.apply(person);  // 输出:Alice

const boundGreet = greet.bind(person);
boundGreet();  // 输出:Alice

实际应用

事件处理中的 this

在事件处理器中,this 通常指向触发事件的元素。在传统的函数表达式中,this 指向事件的目标元素。在箭头函数中,this 会继承外部作用域的 this

1
2
3
4
5
6
7
8
9
10
11
const button = document.querySelector('button');

// 普通函数
button.addEventListener('click', function() {
  console.log(this);  // `this` 指向 button 元素
});

// 箭头函数
button.addEventListener('click', () => {
  console.log(this);  // `this` 指向外部作用域的 `this`
});

类中的 this

在 JavaScript 类中,this 总是指向当前类的实例对象。它与构造函数的行为类似,用于引用实例的属性和方法。

1
2
3
4
5
6
7
8
9
10
11
12
class Person {
  constructor(name) {
    this.name = name;
  }

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

const alice = new Person('Alice');
alice.greet();  // 输出:Hello, Alice

深入理解 JS —— this 关键词
http://xiaowhang.github.io/archives/1253991442/
作者
Xiaowhang
发布于
2025年2月19日
许可协议