Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Two methods I've seen (I know there are more) of using an IIFE:

(function(){
    console.log(this);
}).call(this);

(function(){
    console.log(this);
})();

Is there any reason to use .call(this) on the first one? Won't (); yield the same context within the function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
239 views
Welcome To Ask or Share your Answers For Others

1 Answer

That depends on where the code is executed.

.call(this) explicitly sets the this to the object you pass to .call. Only using (); will set this to window (or to undefined in strict mode).

If the code is executed in global scope it will be the same. If not, then you will get different results if this does not refer to window (or is undefined).

Example:

var obj = {
   foo: function() {
       (function(){
           console.log(this); // this === obj
       }).call(this); // this === obj

       (function(){
           console.log(this); // this === window
       })();
   }
};

obj.foo();

More information about this on MDN


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...