'this' 指的是在方法内部定义的 IIFE 内部定义的内部箭头函数是什么?

What does 'this' refer to inside arrow functions that are defined inside IIFEs that are defined inside a method?

我的理解是箭头函数不会重新绑定 this,那么为什么它会根据调用方式引用不同的对象?

const foo = {
  speak() {
    (() => {
      console.log(this);
    })();
  }
};

foo.speak(); // Logs foo

const speak = foo.speak;

speak(); // Logs the global object

感谢您的宝贵时间!

箭头函数保留 this 的词法值。这意味着,this 的值取决于箭头函数的定义方式,而不取决于箭头函数的调用方式。

您在此处看到的不一致行为是因为每次调用函数 speak 时都会“定义”内部箭头函数。在那个定义点,箭头函数捕获 this 的当前值,这对于 foo.speak()speak() 是不同的。

附带说明一下,这似乎是 JavaScript 琐事。我不希望“真正的”代码库有这种片段。

只有在每次调用 speak 时才会定义和执行箭头函数。第一次调用它是作为 foo 上的方法,因此 this 绑定到 foo。第二次调用时,this 就是 window。与此版本比较:

const foo = {
  speak: () => {
      console.log(this);
  }
};

foo.speak(); 

const speak = foo.speak;

speak(); 

其中 speak 函数 箭头函数,因此 this 会立即绑定到 window 两个调用的对象。

我相信发生的事情是,当您将函数分配给 const 变量时,它会失去作用域。

当您调用 foo.speak() 时,speak 函数在 foo 的上下文中是 运行ning,而当您 运行 speak()将foo.speak函数赋给const变量后,该函数在全局(window)对象的上下文中是运行ning .

MDN 声明:

the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this