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?

Answers:

Answer

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

Answer

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.

Answer

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
})(this);

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

Answer
C={
    descript: "I'm C!<br>",
    F: function() {
        //set this to the caller context's 'this'
        (function() {
            document.write(this.descript);
        }).call(this);

        //set this to 'window' or 'undefined' depend the mode
        (function() {
            document.write(this.descript);
        })();

        //member function's 'this' is the object self
        document.write(this.descript);
    }
}

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

C.F();

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.