如何解决在 JS 中,如何访问任何给定对象的给定属性路径?
为了让事情更清楚,这里有一个例子。我试图把所有东西都剥离到骨头上,只保留相关的细节。这是一个带有一些属性和子属性的虚拟类 Person
:
class Person {
height = 100;
hat = {size: 4};
}
现在,我还有一些其他类,其目的是修改 Person
的某些(子)*属性:
class PersonModifier {
constructor(propertyPath,value) {
this.propertyPath = propertyPath; // this is the part I'm a bit lost on
this.value = value; // a numeric value just to demonstrate how this class would work
}
actUpon(person) { // modifies a quantitative attribute of Person by a given amount
person.(this.propertyPath) += value;
}
}
我知道 actUpon
方法中的唯一一行代码在语法上不起作用,我希望我明白我要做什么。我想它类似于 Person.prototype.whatever
,但我想将它用于属性而不是方法。
以下是上述类的实例示例,其目的是将一个人的帽子大小减少 2:
let hatShrinker = new PersonModifier(.hat.size,-2);
同样,这显然在语法上不起作用,所以这是我的问题:
如何存储和使用属性路径(任意深度),以便我可以访问和写入任何对象的此类属性?考虑到我事先知道对象属于哪些类(在本例中为 Person
)。
注意:任何不涉及字符串的解决方案都是首选,因为字符串不受一些重要的 IDE 功能的影响,例如重构和基于动态类型的建议
解决方法
我确实认为您可能被某种字符串困住了。在这个例子中,我使用一个字符串数组来深入对象路径并改变最终对象的最终键。
class PersonModifier {
constructor(propertyPath,value) {
this.propertyPath = propertyPath;
this.value = value;
}
actUpon(person) {
const path = [...this.propertyPath];
const prop = path.pop();
const obj = path.reduce((acc,el) => {
return acc[el];
},person);
obj[prop] += this.value;
}
}
const hatShrinker = new PersonModifier(["hat","size"],-2);
const person = {
hat: {
size: 4
}
};
hatShrinker.actUpon(person);
console.log(person);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。