我有一个看起来像这样的课程
export default class {
constructor () {
this.store = {}
}
setX (x, y) {
this.store[x] = y
}
}
当获得未定义的值时,我如何在this.store
上定义一个getter来返回0
?
让我举个例子:
setX('a', 1)
将把this.store['a']
设置为1
然后this.store['a']
会像预期的那样返回1
。
但this.store['b']
将返回undefined
,但我希望吸气者返回0
(并且可能会调用setX('b', 0)
,还不确定)。
我知道我可以使用Object.defineProperty
来定义一个自定义的getter,我无法绕过如何访问store
对象的任意的,尚未定义的属性。
这是完全可能还是我必须像这样使用解决方法?
getX (x) {
return this.store[x] || 0
}
我想避免这种情况,因为this.store[x]
似乎更清洁。
当获得
this.store
值时,我如何在0
上定义一个getter来返回undefined
?
除非您能够预测所有可能的属性名称并为其定义getter,否则您需要使用带有Proxy的get
trap,这是ES2015的新版本(并且不能进行polyfilled)。代理在性能方面很昂贵,只有在你真正需要它们时才使用它们。
例:
class Example {
constructor () {
this.store = new Proxy({}, {
get(target, property) {
return property in target ? target[property] : 0;
}
});
}
setX (x, y) {
this.store[x] = y;
}
}
const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.store.a);
console.log("b = " + e.store.b);
当然,如果你将store
设为私有,你只能通过对象上的getX
方法强制访问,这样可以避免使用代理,代价是在每个实例的基础上定义setX
和getX
(目前,private data is coming) :
class Example {
constructor () {
const store = {};
this.setX = (x, y) => {
store[x] = y;
};
this.getX = x => {
return x in store ? store[x] : 0;
};
}
}
const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.getX("a"));
console.log("b = " + e.getX("b"));