Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason behind this self invoking anonymous function variant

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?

like image 504
Sean McMillan Avatar asked Jun 09 '11 02:06

Sean McMillan


People also ask

Why do we need self-invoking function?

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.

What are self-invoking function in JavaScript?

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.

How do you define anonymous function?

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.

Is anonymous function good?

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.


2 Answers

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.

like image 64
user113716 Avatar answered Oct 08 '22 03:10

user113716


.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).

like image 29
matyr Avatar answered Oct 08 '22 04:10

matyr