Javascript 闭包没有按预期工作

标签 javascript node.js scope closures

我在 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 中,顶层的 thisglobal 不同,它是您的模块 。导出。所以当你这样做的时候

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/

相关文章:

javascript - 带有 orm2 和分离模型文件的 Node Express

javascript - 嵌套函数丢失变量引用

javascript - jquery "this"范围作为选择器

javascript - 在 HTML5 中使用模式属性时设置自定义错误消息在 IE 11 中不起作用

javascript - 用于定期聚合数据并使用 Node.js 提供服务的基础设施

windows - 离线安装socket.io

javascript - 在 Javascript 中导入

javascript - 想要根据下拉框选择显示/隐藏div

javascript - Angular 2 FormBuilder禁用复选框选择中的字段

c++ - 在 C++ 上的 if 语句中构造函数初始化后删除字符串