分配为对象属性时,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?
我还想知道为什么当我访问一个不存在的对象属性时,它给出未定义而不是未定义,我认识到未定义是在创建阶段赋予变量的值,执行阶段然后初始化该值,所以如果没有初始化,它保持未定义状态,所以当我访问一个对象属性时,可以说一个a.lastname不存在,不应该返回Java脚本吗?为什么不给出undefined呢?
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?
推荐答案
You can use a getter to implement what you want:
var a={
name:"Rhona",
get check(){
return this.name;
}
}
这篇关于分配为对象属性时,IIFE如何影响其中的此关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!