[英]How do getters work in nested objects when getting a property name from a nested object during object construction?
I want to get a nested property name in an object during object construction.我想在 object 构造期间在 object 中获取嵌套属性名称。
What am I doing wrong?我究竟做错了什么? How do I get the expected output:
'c'
from the nested object?如何从嵌套的 object 中获取预期的 output:
'c'
?
const obj = {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: "c"
Confirmed.确认的。 The above starting example works.
上面的起始示例有效。
Now, I want to add nesting ( obj.level1
).现在,我想添加嵌套 (
obj.level1
)。 This is where things fall apart.这就是事情分崩离析的地方。
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: undefined
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.level1.log.length - 1];
}
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: undefined
Your latest
function exists on the level1
depth.您
latest
的 function 存在于level1
深度。 So the following works:所以以下工作:
console.log(obj.level1.latest)
However, if that's not your intention, you should write your object as such.但是,如果这不是您的意图,您应该这样写您的 object。
const obj = {
level1: {
log: ['a', 'b', 'c']
},
get latest() {
return this.level1.log.at(-1);
}
};
In your modifications obj
doesn't have latest
getter.在您的修改中,
obj
没有latest
的吸气剂。 It's in child object level1
, so just try logging obj.level1.latest
.它在孩子 object
level1
中,所以只需尝试记录obj.level1.latest
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.