关于 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 却不指代 global ?
最佳答案
But when I run the same code in Node I get different result:
没错。 Node 中的代码不在全局范围内运行,它在为节点“模块”创建的范围内运行,其中 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
成为对正在创建的对象的引用,但它没有t; 事实上,有 no way 来引用从初始化程序中创建的对象)。
(在这种特殊情况下,最简单的解决方案是使用 button
而不是 this
,因为该函数也会通过 button
关闭。)
关于javascript - 箭头函数的这个值用作函数表达式或对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43680986/