箭头函数的这个值用作函数表达式或对象的方法

This value of arrow function used as function expression or object's method

关于 arrow functions 和这个值的另一个主题,但我找不到让我困惑的代码的答案。

当我在浏览器的控制台中 运行 此代码时,结果为真:

var f = () => { return this; };
f() === window;                // true
f()                            // Window

但是当我 运行 在 Node 中使用相同的代码时,我得到了不同的结果:

var f = () => { return this; };
console.log(f() === global);    // false
console.log(f() === undefined); // false
console.log(f());               // {}

另外当一个对象被定义时:

let button = {
    isClicked: false,
    click: () => { this.isClicked = true }
}

console.log(button.isClicked);   // false
button.click();
console.log(button.isClicked);   // false

在 Node 中执行此行时,结果未定义:

console.log(global.isClicked);   // undefined

但是在浏览器中执行,结果为真:

console.log(window.isClicked);    // true

为什么当代码在浏览器中执行时,this 引用 window 对象,但在 Node 中执行时,this 不引用全局?

But when I run the same code in Node I get different result:

没错。 Node 中的代码在全局范围内不是 运行,它在为节点 "module" 创建的范围内是 运行,其中 this 不引用全局对象,它引用模块的导出(又名 module.exports)。有关 Node 模块的更多信息 here.

Also when an object is defined

this 在对象初始值设定项中没有不同的含义。您的示例代码:

let button = {
    isClicked: false,
    click: () => { this.isClicked = true }
};

...正在执行此代码的操作:

let button = {
    isClicked: false
};
button.click = () => { this.isClicked = true };

在这两种情况下,click 函数都会在 this 上关闭,因为它是我们创建 button 的地方。 this 不会改变初始化程序中的含义,但代码假定它确实如此(具体来说,代码假定 this 成为对正在创建的对象的引用,但它没有;事实上,有no way 引用从初始化程序中创建的对象。

(在该特定情况下,最简单的解决方案是使用 button 而不是 this,因为该函数也会在 button 上关闭。)