我想在数组中包装值,只要它们设置在我的对象上,但我想保留“全局”对象命名空间CLEAN
问题是我有8个具有相同要求的道具列表
我不希望对象被大量get
和set
以及this._left
污染,以避免在设置由setter监视的同一道具时出现无限循环。 ...
例如:
class Tree {
constructor (config) {
this.left = config.left || [this];
this.right = config.right || [this];
this.child = config.child || [this];
this.parent = config.parent || [this];
this.somethingElse = config.somethingElse || [this];
// etc.
}
}
myObj = new Tree();
myObj.left = 2;
我想确保myObj.next === [2]
我的尝试(太污染了):
['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(direction => {
Object.defineProperty(this, prop, {
set: (val) => {
if (!Array.isArray(val)) {
this['_' + prop] = [val]
} else {
this['_' + prop] = val;
}
},
get: (val) => {
return this['_' + prop];
}
});
});
答案 0 :(得分:1)
没有setter / getters你就不能拥有setter / getter。但是,您不一定需要那些带下划线前缀的属性来存储值:
['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(prop => {
var value = [this];
Object.defineProperty(this, prop, {
set(val) {
if (!Array.isArray(val)) {
val = [val];
}
value = val;
},
get(val) {
return value;
},
enumerable: true,
configurable: true
});
});