How IIFE affects this keyword inside it when assigned as object properties

只谈情不闲聊 提交于 2021-01-20 13:10:21

问题


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

An empty string I expected it to return Rhona,it didn't give undefined or null but an empty string whats going on here?

And i also want to know why when I access an objects property which isn't there it gives undefined instead of giving not defined I recognize undefined is the value given to variables at creation phase,execution phase then initializes the value so if there is no initialization it stays undefined so when i access an object property lets say a.lastname which isn't present shouldn't java script return not defined why is it giving undefined instead?


回答1:


You can use a getter to implement what you want:

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



回答2:


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



来源:https://stackoverflow.com/questions/50315592/how-iife-affects-this-keyword-inside-it-when-assigned-as-object-properties

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