While looking at code on github, I found the following:
(function() {
}).call(this);
This is clearly a self invoking anonymous function. But why is it written this way? I'm used to seeing the canonical variant (function() {})()
.
Is there any particular advantage to using .call(this)
for a self invoking anonymous function?
Edit: 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?
(function() {}).call(this);
could set thethis
in the anonymous to the caller contextthis
, in above isC
.(function() {})();
will setthis
towindow
orundefined
depend the mode.By default, invoking a function like
(function(){/*...*/})()
will set the value ofthis
in the function towindow
(in a browser) irrespective of whatever the value ofthis
may be in the enclosing context where the function was created.Using
call
allows you to manually set the value ofthis
to whatever you want. In this case, it is setting it to whatever the value ofthis
is in the enclosing context.Take this example:
http://jsfiddle.net/LWFAp/
You can see that we were able to manually set the value of
this
to the object referenced by theobj
variable.Self-invoking function are useful to execute its content immediately when the script is loaded. This is convenient to initialize global scope elements.
By using:
then this in the scope of the code (probaby the global object) is set as the function's this object. As far as I can tell, it's equivalent to:
In a browser, usually window is (or behaves as if it is) an alias for the global object.
.call(this)
(was actually just()
until I changed it) ensures your top levelthis
to be consistent through strict mode,--bare
option and/or the running environment (where top levelthis
doesn't point to global object).