Reason behind this self invoking anonymous function variant

While looking at code on github, I found the following:

(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() {})().

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?



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


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 = {

(function() {
    alert( ); // "bar"
}).call( obj );

You can see that we were able to manually set the value of this to the object referenced by the obj variable.


By using:

> (function() {
>   ...
> }).call(this);`

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:

(function(global) {
  // global references the object passed in as *this*
  // probably the global object

In a browser, usually window is (or behaves as if it is) an alias for the global object.

    descript: "I'm C!<br>",
    F: function() {
        //set this to the caller context's 'this'
        (function() {

        //set this to 'window' or 'undefined' depend the mode
        (function() {

        //member function's 'this' is the object self

window.descript="I'm window!<br>";


(function() {}).call(this); could set the this in the anonymous to the caller context this, in above is C.(function() {})(); will set this to window or undefined depend the mode.


Self-invoking function are useful to execute its content immediately when the script is loaded. This is convenient to initialize global scope elements.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.