这种自我调用匿名函数变体的原因 [英] Reason behind this self invoking anonymous function variant
问题描述
在github上查看代码时,我发现了以下内容:
While looking at code on github, I found the following:
(function() {
}).call(this);
这显然是一个自我调用的匿名函数。但是为什么这样写呢?我习惯看到规范变体(function(){})()
。
This is clearly a self invoking anonymous function. But why is it written this way? I'm used to seeing the canonical variant (function() {})()
.
对于自我调用匿名函数使用 .call(this)
特别有利吗?
Is there any particular advantage to using .call(this)
for a self invoking anonymous function?
编辑:看起来像一些commonjs环境设置这个
到模块顶层的非全局值。
It looks like some commonjs environments set this
to a non-global value at the top level of a module. Which ones, and what do they set this
to that you might want to preserve?
推荐答案
.call(this)
(实际上只是()
,直到我改变它)通过严格模式, - bare
选项和/或运行环境(其中顶级 code> this
不指向全局对象)。
.call(this)
(was actually just ()
until I changed it) ensures your top level this
to be consistent through strict mode, --bare
option and/or the running environment (where top level this
doesn't point to global object).
这篇关于这种自我调用匿名函数变体的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!