问题描述
我最近一直在玩node.js而且我在模块的全局范围内遇到了关于 this
的使用的奇怪行为。
I've been toying with node.js lately and I ran into a weird behavior about the usage of this
in the global scope of a module.
此
绑定到全局范围内的module.exports:
this
is bound to module.exports in the global scope:
console.log(this === exports); // -> true
但此
绑定到全局方法范围:
But this
is bound to global in a method scope:
(function() { console.log(this === global); })(); // -> true
这也会导致这种令人困惑的行为:
This also lead to this confusing behavior:
this.Foo = "Weird";
console.log(Foo); // -> throws undefined
(function() { this.Bar = "Weird"; })();
console.log(Bar); // -> "Weird"
我想解决方案是永远不要使用这个
在全局范围内并显式使用 extends
或 global
,但是有一个逻辑背后的全部这个或者是node.js中的错误或限制吗?
I guess that the solution is to never use this
in the global scope and explicitly use extends
or global
instead, but is there a logic behind all this or is it a bug or limitation in node.js?
推荐答案
在处理一个简单的CommonJS模块实现时,我不得不想一想在模块的全局范围内如何处理这个
;规范没有解决这个问题。
In working on a simple CommonJS modules implementation, I had to think about what to do with this
in the global scope of the module; it's not addressed by the spec.
我首先将它设置为 exports
对象,因为我认为这会有用,但是稍后我需要模块化使用这个
来获取全局对象的句柄,所以我更改了这个
返回为全局对象提供尽可能正常的模块代码的环境。
I also set it up as the exports
object at first, because I thought that would be useful, but later found some code I needed to "modulize" that was using this
to get a handle to the global object, so I changed this
back to the global object to provide as close of an environment to "normal" as possible for module code.
我们只能猜测为什么节点的设置方式与(或询问作者),但我的猜测只是因为它似乎是一个有用的想法,类似于你可以给模块
对象的方式<$ c在节点中$ c> exports 属性并将其反映在模块的实际 exports
中(此行为也不是规范的一部分,但不是也不要反对它。
We can only guess at why node is set up the way it is (or ask the author), but my guess is it was done simply because it seemed like a useful idea, similar to the way you can give the module
object an exports
property in node and have it reflected in the module's actual exports
(this behavior also isn't part of the spec, but doesn't go against it either).
关于这个
引用的部分问题函数中的全局
,正如其他答案所解释的那样,这就是这个
的工作方式;它不是特定于节点的行为,它是一种奇怪的javascript行为。
As for the part of your question about this
referencing global
in functions, as the other answers explain, that's just the way this
works; it's not a node-specific behavior, it's a weird javascript behavior.
这篇关于node.js:在全局范围中混淆使用'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!