【发布时间】:2012-02-28 15:29:37
【问题描述】:
我最近一直在玩 node.js,但我遇到了一个关于在模块的全局范围内使用 this 的奇怪行为。
this 绑定到全局范围内的 module.exports:
console.log(this === exports); // -> true
但this 在方法范围内绑定到全局:
(function() { console.log(this === global); })(); // -> true
这也导致了这种令人困惑的行为:
this.Foo = "Weird";
console.log(Foo); // -> throws undefined
(function() { this.Bar = "Weird"; })();
console.log(Bar); // -> "Weird"
我想解决方案是永远不要在全局范围内使用this,而是显式使用extends 或global,但是这一切背后是否存在逻辑,或者它是node.js 中的错误或限制?
【问题讨论】:
标签: javascript node.js