Reason behind this self invoking anonymous function variant

浪尽此生 提交于 2019-11-26 04:42:44

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/6287511/reason-behind-this-self-invoking-anonymous-function-variant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!