[英]Accessing calculated property in javascript object
Why does the console print undefined when I access age property directly.为什么当我直接访问年龄属性时控制台打印未定义。 I have to print calcAge function first in order to get the value.
我必须先打印 calcAge function 才能获得价值。
const Osama = {
firstName: 'osama',
lastName: 'Shaikh',
birthyear: 1999,
job: 'developer',
friends: ['michael', 'peter', 'steven'],
haslicense: true,
calcAge: function () {
this.age = 2021 - this.birthyear;
return this.age;
},
};
console.log(Osama.age);
That object doesn't have an age
property to begin with. object 一开始就没有
age
属性。
You only assign it when you run the calcAge
method.只有在运行
calcAge
方法时才分配它。
It seems like you're looking to assign a getter
for the age
property.似乎您正在为
age
属性分配一个getter
。
const Osama = { birthyear: 1999, get age() { console.log('in getter'); return 2021 - this.birthyear; }, }; console.log(Osama.age); // in getter, 22 console.log(Osama.age); // in getter, 22
Or, to calculate the age only on first access and replace it with a static property you can use a self-overwriting getter.或者,要仅在首次访问时计算年龄并将其替换为 static 属性,您可以使用自覆盖getter。
const Osama = { birthyear: 1999, get age() { console.log('in getter'); delete this.age; return (this.age = 2021 - this.birthyear); }, }; console.log(Osama.age); // in getter, 22 console.log(Osama.age); // 22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.