DEV Community

Leo
Leo

Posted on • Edited on

JavaScript 中的this

在 JavaScript 中,this 是一个非常重要的关键字,代表当前执行上下文中的对象。它的值根据函数的调用方式、作用域以及调用时的上下文有所不同。

this 的规则

1. 全局上下文中的 this

在全局作用域中,this 指向全局对象。在浏览器中,this 指向 window 对象,在 Node.js 中,this 指向 global 对象。

console.log(this); // 在浏览器中会输出 window 对象
Enter fullscreen mode Exit fullscreen mode

2. 普通函数中的 this

在普通函数中,this 的值由函数如何被调用决定。通常情况下,普通函数中的 this 指向全局对象(在严格模式下 this 是 undefined)。

function showThis() {
  console.log(this);  // 非严格模式下,指向全局对象(浏览器中为 window)
}

showThis();
Enter fullscreen mode Exit fullscreen mode

严格模式 ('use strict') 中,this 不会指向全局对象,而是 undefined。

'use strict';

function showThis() {
  console.log(this);  // undefined
}

showThis();
Enter fullscreen mode Exit fullscreen mode

3. 对象方法中的 this

当 this 用于对象的方法时,this 指向调用该方法的对象。

const person = {
  name: 'Alice',
  greet: function() {
    console.log(this.name);  // this 指向 person 对象
  }
};

person.greet();  // 输出 "Alice"
Enter fullscreen mode Exit fullscreen mode

4. 构造函数中的 this

在构造函数中,this 指向新创建的实例对象。

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

const person = new Person('Alice');

console.log(person.name);  // 输出 "Alice"
Enter fullscreen mode Exit fullscreen mode

5. 箭头函数中的 this

箭头函数没有自己的 this,它会从外部上下文(即定义时的作用域)继承 this 的值。换句话说,箭头函数的 this 是静态的,它绑定了外部上下文的 this。

const obj = {
  name: 'Alice',
  greet: function() {
    setTimeout(() => {
      console.log(this.name);  // this 会继承 greet 方法的上下文,指向 obj
    }, 1000);
  }
};

obj.greet();  // 输出 "Alice"
Enter fullscreen mode Exit fullscreen mode

6. call、apply 和 bind

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

  • call 和 apply:都可以改变 this 的指向,并立即调用函数。
  • call 需要将参数一个个传递。
  • apply 接受一个数组作为参数。
function greet() {
  console.log(this.name);
}

const person = { name: 'Alice' };

greet.call(person);  // 输出 "Alice"

greet.apply(person);  // 输出 "Alice"
Enter fullscreen mode Exit fullscreen mode
  • bind:返回一个新的函数,并且固定 this 的指向。
const boundGreet = greet.bind(person);

boundGreet();  // 输出 "Alice"
Enter fullscreen mode Exit fullscreen mode

7. 事件处理中的 this:

在事件处理函数中,this 通常指向触发事件的 DOM 元素。

const button = document.querySelector('button');

button.addEventListener('click', function() {
  console.log(this);  // 这里 this 指向 button 元素
});
Enter fullscreen mode Exit fullscreen mode

总结

  • this 的值是动态的,依赖于函数如何调用。
  • 在普通函数中,this 指向全局对象(在严格模式下为 undefined)。
  • 在对象方法中,this 指向调用该方法的对象。
  • 在构造函数中,this 指向新创建的实例。
  • 箭头函数没有自己的 this,它继承了外部上下文的 this。
  • 可以使用 call、apply 和 bind 来显式控制 this 的指向。

Top comments (0)