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?
Self-invoking functions are useful for initialization tasks and for one-time code executions, without the need of creating global variables. Parameters can also be passed to self-invoking functions as shown in the example below.
Self-Invoking Functions A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Nope, anonymous functions are used all over the place in JavaScript across the web. It may make debugging a little more difficult in spots, but not nearly enough to say that they shouldn't be used. For example, JQuery makes extensive use of them.
By default, invoking a function like (function(){/*...*/})()
will set the value of this
in the function to window
(in a browser) irrespective of whatever the value of this
may be in the enclosing context where the function was created.
Using call
allows you to manually set the value of this
to whatever you want. In this case, it is setting it to whatever the value of this
is in the enclosing context.
Take this example:
var obj = { foo:'bar' }; (function() { alert( this.foo ); // "bar" }).call( obj );
http://jsfiddle.net/LWFAp/
You can see that we were able to manually set the value of this
to the object referenced by the obj
variable.
.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With