简体   繁体   中英

Does an IIFE's this always point towards the global object?

I have a code snippet down below.

var obj = {
 name: "Mohit",
 func: function(){
  var self = this;
  (function(){
    console.log(this.name);
    console.log(self.name)
  })()
 }
}

After executing obj.func(), I get the first console.log to be undefined while I get the second one to be Mohit.

Does this mean that an IIFE always binds the this to the global window object?

How defining self to be this is the binding for the IIFE happening to the obj?

Any function you call without a clear reference for this will have this set to the global object, or in "strict" mode to undefined (which is not the case in your example).

You could explicitly ensure that this is bound to obj if you wanted:

 var obj = { name: "Mohit", func: function(){ var self = this; (function(){ console.log(this.name); console.log(self.name) }).call(this) } } obj.func();

By using .call(this) , you provide a value for this inside the called function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM