我只是想知道是否可以像下面这样在同级对象中引用自身(对象)值?
[
{
"name": "Zulh",
"name_uppercase": uppercase(self.name) // expects ZULH
},
{
"name": "John",
"name_uppercase": uppercase(self.name) // expects JOHN
}
]
注意:
为简洁起见,省略了 uppercase
的代码。在我的真实代码中,它执行的是同步复杂的操作,实际上并不是像那样简单的字符串大小写操作。
最佳答案
使用 GETTER
如果你想让它保持动态,即使你改变了 name
属性也让它工作,你可以使用 GETTER做这种事:
const names = [
{
"name": "John",
get name_uppercase() {
return this.name.toUpperCase();
}
}
]
console.log(names[0].name_uppercase)
多个对象的 GETTER
您不必为每个属性都手动编写!使用 .forEach
:
const names = [
{
"name": "John"
},
{
"name": "Mike"
}
]
names.forEach(object => {
Object.defineProperty(object, 'nameUppercase', {
get: function() { return this.name.toUpperCase() }
});
});
console.log(names[0].nameUppercase)
console.log(names[1].nameUppercase)
使用类和 GETTER
或者正如@Rajesh 指出的那样,您可以改用类:
class Person {
constructor(name) {
this.name = name;
}
get nameUpperCase() {
return this.name.toUpperCase();
}
}
const names = [ new Person("John"), new Person("Mike")];
console.log(names[0].nameUpperCase);
console.log(names[1].nameUpperCase);
关于javascript - 如何访问其他对象兄弟的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51281200/