问题描述
我目前正在尝试设置一个类,其中属性是另一个对象的数组(由另一个类定义)。
我使用 set/get 来管理值。我也在构造函数中初始化它们。
我想要实现的是向同一个属性添加内联函数,让整体生活更轻松。但是,我觉得我在这里使用了错误的方法。
class _MainObject {
constructor(){
this._property = [];
this.property= {
add(value,index){
if (value.constructor.name !== '_SubObject'){
return;
}
this._property.splice(index,value);
},remove(value){
if (value.constructor.name !== '_SubObject'){
return;
}
const index = this._property.findindex((pId) => pId === value.id);
this._property.splice(index,1);
}
};
}
set property(value){
if (Array.isArray(value)){
value.map((el) => {
if (el.constructor.name !== '_SubObject') return;
});
this._property = value;
}
//Tried a bunch of stuff here to assign the default object from above on the first initialization.
}
get property(){
return this._property;
}
}
每当构造函数初始化属性时,它都会触发“set”并且不会将函数分配给“property”本身。
我想要 obj._property 中的实际数据,但通过调用 obj.property 获取。我也希望能够调用 obj.property.add()。
这在某种程度上肯定是可行的,但我不知道如何做到。
理想情况下,我想使用 ES5+ 语义。
预先感谢您提供的任何帮助。
解决方法
class Property {
constructor(){
this.value = [1,2,3];
}
add(x){
this.value = [...this.value,x]
}
}
class _MainObject {
constructor(){
this._property = new Property();
}
set property(value){
if (Array.isArray(value)){
this._property = value;
}
}
get property(){
return this._property;
}
}
const a = new _MainObject()
console.log(a.property)
a.property.add(4)
console.log(a.property)
您需要将属性包装到它自己的类中。
这是执行此操作的唯一方法,因为您不能拥有与此处解释的相同名称的 getter 和函数或属性:
Is there a way to use the same name for both a setter method and class property?
Differentiate between property and method with same name
Can JS have getters and setters methods named same as property?