我在 nodejs 上运行这段代码。我想知道为什么执行时闭包不打印字符串“Globals”?闭包中的 this
不是指向全局作用域吗?
// Running on NodeJS, not in a browser!
this.name = "Globals";
function Person(name) {
this.name = name;
this.namePrinter = function() {
return function() {
console.log(this.name);
}
}
}
var p = new Person("Faiz");
p.namePrinter()(); // prints undefined. Shouldn't it print Globals?
console.log(this.name); // prints Globals
最佳答案
您的示例在浏览器中按预期工作,但在 node.js 中,顶层的 this
与 global
不同,它是您的模块 。导出
。所以当你这样做的时候
this.name = "Globals";
它将 name: Globals
分配给 module.exports
,而不是 global
对象。
现在,当你写的时候
p.namePrinter()();
这与:
func = p.namePrinter();
func();
该函数是未绑定(bind)的(= 在它之前没有 object.
),所以它的 this
将是 global
对象。但是那里没有 name
...
在浏览器中,您的顶级代码在全局对象(即 window
)的上下文中执行,这与未绑定(bind)函数使用的对象相同。这就是您的代码段有效的原因。
关于Javascript 闭包没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812809/