JavaScript 中的 this 关键字

54 阅读2分钟

1. this 是什么?

this 是 JavaScript 中的一个特殊关键字,它在函数被调用时自动绑定到一个对象上。this 的值取决于函数的调用方式,而不是函数的定义位置。

2. this 指向什么?

this 的指向取决于函数的调用方式:

  • 默认绑定:在独立函数调用中,this 指向全局对象(浏览器中是 window,Node.js 中是 global)。严格模式下为 undefined
  • 隐式绑定:作为对象方法调用时,this 指向调用该方法的对象。
  • 显式绑定:使用 call(), apply()bind() 方法时,this 指向指定的对象。
  • new 绑定:使用 new 调用构造函数时,this 指向新创建的对象。
  • DOM 事件处理程序:在事件处理函数中,this 通常指向触发事件的元素。

3. 箭头函数中的 this

箭头函数没有自己的 this 绑定,它会捕获其所在上下文的 this 值作为自己的 this 值。这意味着:

  • 箭头函数内部的 this 与定义时所在的作用域的 this 相同
  • 无法通过 call(), apply()bind() 改变箭头函数的 this
  • 不适合用作对象方法(如果需要访问对象自身)
  • 适合用在需要保持 this 不变的场景,如回调函数

5 个关于 this 的面试题

题目 1:基本 this 指向

const obj = {
  name: 'Alice',
  greet: function() {
    console.log(this.name);
  }
};

obj.greet(); // 输出什么?
const greet = obj.greet;
greet(); // 输出什么?

题目 2:箭头函数的 this

const obj = {
  name: 'Bob',
  greet: () => {
    console.log(this.name);
  }
};

obj.greet(); // 输出什么?

题目 3:this 与回调函数

const obj = {
  name: 'Charlie',
  greet: function() {
    setTimeout(function() {
      console.log(this.name);
    }, 100);
  }
};

obj.greet(); // 输出什么?

题目 4:bind 方法

const obj1 = {
  name: 'David',
  greet: function() {
    console.log(this.name);
  }
};

const obj2 = { name: 'Eve' };
const greet = obj1.greet.bind(obj2);

obj1.greet(); // 输出什么?
greet(); // 输出什么?

题目 5:构造函数中的 this

function Person(name) {
  this.name = name;
  setTimeout(function() {
    console.log(this.name);
  }, 100);
}

new Person('Frank'); // 输出什么?

答案

  1. 'Alice'undefined(或全局对象的 name 属性)
  2. undefined(箭头函数继承外层作用域的 this
  3. undefined(回调函数中的 this 默认指向全局对象)
  4. 'David''Eve'bind 创建了绑定 this 的新函数)
  5. undefined(构造函数中的回调函数 this 指向全局对象)