Reason behind this self invoking anonymous functio

2019-01-04 00:25发布

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?

5条回答
唯我独甜
2楼-- · 2019-01-04 01:05
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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-04 01:10

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.

查看更多
爷的心禁止访问
4楼-- · 2019-01-04 01:11

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

查看更多
【Aperson】
5楼-- · 2019-01-04 01:14

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.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-04 01:18

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

查看更多
登录 后发表回答