【问题标题】:Javascript closure not working as expectedJavascript 关闭没有按预期工作
【发布时间】:2016-06-19 04:15:34
【问题描述】:

我在 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

【问题讨论】:

    标签: javascript node.js scope closures


    【解决方案1】:

    您的示例在浏览器中按预期工作,但在顶层的 node.js thisglobal 不同,它是您的模块 .exports。所以当你这样做时

    this.name = "Globals";
    

    它将name: Globals 分配给module.exports,而不是global 对象。

    现在,当你写作时

    p.namePrinter()();
    

    同理:

    func = p.namePrinter();
    func();
    

    该函数未绑定(= 在它之前没有 object.),因此它的 this 将是 global 对象。但是那里没有name...

    在浏览器中,您的顶级代码在全局对象(即window)的上下文中执行,这与未绑定函数使用的对象相同。这就是你的 sn-p 工作的原因。

    【讨论】:

    • setTimeout 是如何得到答案的?我已经修好了,但我很好奇。这真的是骗子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2020-11-25
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多