为什么在web和nodejs上运行JavaScript会有不同的输出?

我已经更新了我的Node.Jsversion 7.6.0 ,另一方面运行谷歌浏览器version 57.0

当我运行JavaScript代码片段时,会得到如下两个不同的结果:

  'use strict' var obj = { id: "awesome", cool: function coolFn() { console.log(this.id); } }; var id = "not awesome"; obj.cool(); //awsome setTimeout(obj.cool, 100); 

结果在铬:

 awesome not awesome 

结果在node.js上:

 awesome undefined 

logging到https://nodejs.org/en/docs/es6/我甚至使用了--harmony标志,但是node.js的结果没有改变。

当节点运行你的文件时,它被当作一个模块来处理, 文档说它被有效的包装起来了:

 (function (exports, require, module, __filename, __dirname) { // Your module code actually lives in here }); 

这意味着var id = "not awesome"; 在该模块包装器中作用域,而不是作为全局对象上的属性创build的。

当定时器触发时, this被设置为全局对象。 因此,在浏览器中, var id在全局范围内,您可以看到它,而在节点中,它是undefined

如果我们将代码封装在浏览器中的函数中,则会看到相同的结果:

 (function() { 'use strict' var obj = { id: "awesome", cool: function coolFn() { console.log(this.id); } }; var id = "not awesome"; obj.cool(); //awsome setTimeout(obj.cool, 100); })();