解释 JavaScript 中的 this 关键字

JavaScript 中的 this 关键字用于引用当前执行上下文的对象。

JavaScript 中等 基础 作用域 JS基础

在 JavaScript 中,this 关键词是指向当前执行上下文对象的关键字,它的值由函数的调用方式决定,而非定义位置,从而支持动态绑定机制。

1. this 的核心特性

  • 动态绑定this 的值在函数执行时确定,包括调用方法、环境以及 strict mode 的设置。
  • 严格模式影响:默认函数中,this 指向全局对象(浏览器为 window);但在严格模式下("use strict"),其值为 undefined,避免意外错误。
  • 词法作用域例外:箭头函数中,this 被捕获并指向其定义时外层作用域的 this,而非动态上下文。

2. this 的常见使用场景

  • 全局作用域:默认指向全局对象(window),适用于独立函数调用:
    console.log(this === window); // 输出 true(非严格模式)
    
  • 对象方法中this 指向调用该方法的对象:
    const person = {
      name: 'John',
      greet: function() {
        console.log(this.name); // 输出 'John'(指向 person)
      }
    };
    person.greet(); // 调用对象方法时 this 绑定 person
    

    注意:若方法被赋值后独立调用,this 回到全局作用域(例如 const greet = person.greet; greet(); 输出 undefined)。

  • 构造函数中this 指向 new 创建的新实例对象:
    function Person(name) {
      this.name = name; // this 指向新实例
    }
    const alice = new Person('Alice');
    console.log(alice.name); // 输出 'Alice'
    
  • 事件处理函数中:DOM 事件触发时,this 指向被点击元素(例如 <button onclick="console.log(this)"> 返回按钮元素)。

3. 显式修改 this 的方法

调用 apply(), call(), 或 bind() 可以强制设置 this 指向,例如:

  function displayMessage() {
    console.log(this.message);
  }
  const context1 = { message: 'Hello' };
  const context2 = { message: 'World' };

  displayMessage.call(context1);  // 输出 'Hello'(this 设置为 context1)
  const boundFunc = displayMessage.bind(context2);
  boundFunc();                     // 输出 'World'(bind 永久绑定)

未指定参数时,非严格模式 apply() 默认指向全局对象;严选模式下为 undefined