当分配为对象属性时,IIFE 如何影响其中的这个关键字 [英] 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 ""
一个空字符串我希望它返回 Rhona,它没有给出 undefined 或 null 而是一个空字符串这里发生了什么?
An empty string I expected it to return Rhona,it didn't give undefined or null but an empty string whats going on here?
而且我还想知道为什么当我访问一个不存在的对象属性时它给出 undefined 而不是给出未定义我认识到 undefined 是在创建阶段赋予变量的值,执行阶段然后初始化该值,所以如果没有初始化它保持未定义所以当我访问一个对象属性时可以说不存在的 a.lastname 不应该 java 脚本返回未定义为什么它给出未定义?
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?
推荐答案
您可以使用 getter 来实现你想要的:
You can use a getter to implement what you want:
var a={
name:"Rhona",
get check(){
return this.name;
}
}
这篇关于当分配为对象属性时,IIFE 如何影响其中的这个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!