2016-03-05 114 views
3

我在nodejs上运行此代码。我想知道为什么在执行时不关闭字符串'Globals'?封闭体中的this不是指向全局范围吗?Javascript关闭按预期工作

// 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 

回答

5

你的榜样按预期正常运行在浏览器中,但在顶层的node.js this是不一样的global,这是你的模块.exports。所以,当你做

this.name = "Globals"; 

它指定name: Globalsmodule.exports,不给global对象。

现在,当你写

p.namePrinter()(); 

是一样的:

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

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

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

+0

^^当然!卫生署。 –

+0

很好地解释了+1 –

+0

'setTimeout'是如何进入答案的?我修好了,但我很好奇。这实际上是一个愚蠢的? –