我最近一直在玩弄node.js,并且遇到了关于使用的奇怪行为this
在模块的全局范围内。
this
在全局范围内绑定到 module.exports:
console.log(this === exports); // -> true
But 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
or global
相反,但这一切背后是否有逻辑,或者是 Node.js 中的错误或限制?
其背后的“逻辑”是,this
总是取决于函数是如何被调用的.
就你而言,你有一个自动执行的匿名函数,this
始终引用全局对象(非严格模式)或undefined
(ES5 严格)。
如果你想访问“外部”this
值,您可以在执行该函数之前存储引用,例如
var outerScope = this;
(function() { outerScope.Bar = "Weird"; })();
console.log(Foo); // -> throws undefined
or re- .bind()
函数的范围是你自己,比如
(function() { this.Bar = "Weird"; }).bind(this)();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)