【发布时间】:2017-11-02 17:03:48
【问题描述】:
var name = "Global";
function funcA() {
var name = "FunA";
return function() {
console.log(this.name);
}
}
funcA()();
我使用节点在终端上运行上面的代码并返回undefined
但在 chrome 控制台中,它将返回 Global。
为什么会这样?
【问题讨论】:
-
对不起,只要编辑代码,它就会打印 Global 然后 undefined,为什么?
-
我在 Node(承认古代 0.12.4)和 Chrome 中都看到了日志消息
Global,后跟返回值undefined。你能展示一下Node做什么的截图吗?在 no 环境中,funcA()()是否有返回值(默认undefined除外,因为缺少returned 值)。function() { console.log(this.name); }里面有零个return语句。 -
另外,请注意the danger of using a global variable called
name,它将在浏览器代码中被字符串化。 (这里没有问题,因为它是一个字符串,但可能会导致其他类型的麻烦。) -
您是否将此代码作为模块运行? (模块中的顶级变量不是全局变量,这可以解释为什么您会看到记录的值不同。)
-
@apsillers 我相信他是通过
node test.js... 运行它的
标签: javascript node.js google-chrome scope