箭头函数的this指向谁

发布于:2025-02-21 ⋅ 阅读:(21) ⋅ 点赞:(0)

先看1个重要原则:

        由Vue管理的函数,一定不要写箭头函数,箭头函数的this就不再是Vue实例了

箭头函数的 this 指向在定义时确定,继承自外层作用域(即定义时的上下文)的 this,且无法通过 callapply  或  bind 改变。以下是关键点总结:

1. 词法作用域的 this

  • 箭头函数没有自己的 this,它使用外层非箭头函数作用域的 this 值。若外层没有函数,则指向全局对象(如 window 或 global)。

  • 示例

    const obj = {
      value: 42,
      getValue: function() {
        // 普通函数中的 this 指向 obj
        const arrowFn = () => this.value;
        return arrowFn();
      }
    };
    console.log(obj.getValue()); // 输出 42

    2. 与普通函数的区别

  • 普通函数this 由调用方式决定(如对象方法、构造函数、事件监听等)。

  • 箭头函数this 固定为定义时的外层 this

  • 示例对比

    // 普通函数(this 指向调用者)
    const obj1 = {
      value: 10,
      fn: function() { console.log(this.value); }
    };
    setTimeout(obj1.fn, 100); // 输出 undefined(this 指向全局)
    
    // 箭头函数(this 继承外层)
    const obj2 = {
      value: 10,
      fn: function() {
        setTimeout(() => console.log(this.value), 100); // 继承外层 this(obj2)
      }
    };
    obj2.fn(); // 输出 10

    3. 无法通过绑定方法修改

  • 使用 callapply 或 bind 无法改变箭头函数的 this

  • 示例

    const outerThis = { name: "Outer" };
    const arrowFn = () => console.log(this.name);
    arrowFn.call({ name: "New" }); // 输出 "Outer"(若外层 this 指向全局则可能输出 undefined)

    4. 对象字面量中的陷阱

  • 对象字面量不创建作用域,内部箭头函数的 this 指向全局。

  • 示例

    const obj = {
      value: "Hello",
      getValue: () => console.log(this.value) // this 指向全局(如 window)
    };
    obj.getValue(); // 输出 undefined(假设外层为全局)

    5. 在构造函数中的行为

  • 箭头函数作为构造函数会报错(不能 new)。

  • 但若在构造函数内定义,箭头函数会继承实例的 this

    function Person() {
      this.age = 0;
      setInterval(() => {
        this.age++; // this 指向 Person 的实例
      }, 1000);
    }
    const p = new Person(); // age 每秒自增

    6.总结

  • 箭头函数的 this:继承自定义时的外层作用域,且不可更改。

  • 使用场景:需要固定 this 时(如回调、事件处理、setTimeout)。

  • 避免场景:需要动态 this 时(如对象方法、构造函数)。

通过理解箭头函数的词法 this 特性,可以更灵活地控制代码中的上下文绑定。