Skip to content Skip to sidebar Skip to footer

How IIFE Affects This Keyword Inside It When Assigned As Object Properties

var a={ name:'Rhona', check:(function(){ return this.name; })(); } console.log(a.check)// This returns '' An empty string I expected it to return R

Solution 1:

The IIFE is executed immediately (that's the first "I"¹). Since you're calling it without doing anything particular to set this, this defaults to the global object (in loose mode) or undefined (in strict mode). (See How does the “this” keyword work?)

You're basically doing this, but without a temporary variable:

var temp = (function() {
    return this.name;
})();
var a = {
    name: "Rhona",
    check: temp
}
console.log(a.check) // This returns ""

The reason you get "" rather than undefined is that you're using loose mode, and so this refers to the global object, which is the window on browsers, and the window has a name property (the name of the current window) which is usually empty ("").


¹ The first "I" in "IIFE" is either "Inline" or "Immediately" depending on who you ask. :-) E.g., "Inline-Invoked Function Expression" or "Immediately-Invoked Function Expression".


Solution 2:

You can use a getter to implement what you want:

var a={
   name:"Rhona",
   get check(){
          return this.name;
            }
   }

Post a Comment for "How IIFE Affects This Keyword Inside It When Assigned As Object Properties"