每当在我的对象上设置值时,我想将它们包装在数组中,但我想保持“全局”对象命名空间干净
问题是我有一个包含 8 个具有相同要求的 Prop 的列表
我不希望对象被大量的 get
和 set
污染,加上 this._left
以避免无限循环当设置由 setter 监控的相同 prop 时......
例如:
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];
}
});
});
最佳答案
如果没有 setter/getter,就不能有 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
});
});
关于javascript - ES6 setter - 保持对象干净//将参数映射到实例对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40143480/