如果 IIFE 只包含一个立即导出到全局作用域的变量声明,为什么还要费心呢?
现在已经是晚上了,所以我的功能可能不太好,但我找到了这段代码,我似乎无法弄清楚为什么它是这样使用的(注意:我明白它的作用,我不明白的是它背后的含义)。
(function() {
var narcissus = {
options: {
version: 185,
},
hostGlobal: this
};
Narcissus = narcissus;
})();
自执行的匿名函数用于避免全局命名空间的污染,但是此代码不需要引入除 Narcissus
之外的其他变量,因此它可以很容易地重写为 Narcissus = { ...};
。我能想到的一些可能的原因是代码的面向未来或实现缺陷。有什么我看不到的吗?
It's late in the evening here so I may not be functioning very well, but I found this piece of code and I can't seem to figure out why it's used like this (NOTE: I understand what it does, what I don't understand is the meaning behind it).
(function() {
var narcissus = {
options: {
version: 185,
},
hostGlobal: this
};
Narcissus = narcissus;
})();
Self-executing anonymous functions are used to avoid pollution of the global namespace, but this code doesn't need to introduce other variables than Narcissus
so it could have very easily be rewritten as Narcissus = {...};
. Some possible reasons I can think of are future-proofing of the code or implementation flaw. Is there something I fail to see?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从可维护性的角度来看,它允许作者稍后在闭包范围中添加代码,这些代码不会在
narcissus
的创建和Narcissus
的分配之间泄漏。尽管在本例中没有任何代码,所以除了上面提到的this
内容之外,我没有看到任何收益。From a maintainability standpoint it allows the author to later add code in a Closure scope that doesn't get leaked between the creation of
narcissus
and the assignment ofNarcissus
. Though in this case there isn't any code there so I don't see any gains other than thethis
stuff mentioned above.您缺少的部分是 javascript 是一种区分大小写的语言,因此
他通过省略
var
关键字将Narcissus
添加到全局范围,或者 Narcissus 已经在全局范围内可用,或Narcissus
已在调用此函数的范围内定义。然后将其定义为匿名函数内的对象 narcissus 。
我无法告诉你他为什么这样做,但看起来他可能已经在
this
引用一个对象的范围内,并且他想设置键hostGlobal
到全局对象而不是当前范围的对象。这就是为什么他将其作为匿名函数运行,因为它们是在全局范围而不是函数范围中执行的。所以在他的代码中
hostGlobal: this
指的是全局对象。当然,他可以只使用
hostGlobal: window
,除非此代码也在非浏览器环境中运行,例如 node.js,其中全局对象是global
而不是窗口
。所以他可能会用一种非常不直观的方法来实现这一目标。希望这有帮助
The part your missing is that javascript is a case sensitive language so
He is adding
Narcissus
to the global scope by omitting thevar
keyword, or Narcissus is already available in the global scope, orNarcissus
has already defined in the scope of where this function is being called.Then defining it as the object
narcissus
inside the anonymous function.I cannot tell you why he is doing this, but it seems like he might already be inside a scope where
this
is referring to an object, and he want to set the keyhostGlobal
to the global object not the currently scoped object.That is why he is running it as an anonymous function, as they are executed in the global scope not function scope. So in his code
hostGlobal: this
is referring to the global object.Of course he could just use
hostGlobal: window
, unless this code is also being run in non browser environments such as node.js where the global object isglobal
notwindow
. So he might be doing it as a very unintuitive method of achieving.Hope this helps