2017-12-18 237 views
3

的任意属性我有一个类,看起来像这样返回一个适合对象

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]看起来非常干净。

回答

3

我如何定义上this.store一个getter来得到一个undefined值时返回0

除非你能预料要支持,并定义为干将他们,要做到这一点,你需要一个Proxyget 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方法的对象,这将避免使用代理服务器在执行访问每个实例定义setXgetX的费用(现在为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"));

+0

是不是最好使用(''的hasOwnProperty),而不是'in'? – Adelin

+1

@Adelin:作为一个全面的声明?一点都不。这完全取决于你在做什么。在这里,我们从一个将会遍历原型链的对象中获取属性,所以使用遍历原型链的操作是合理的。 –

+0

这真的很有帮助!谢谢! – Decay42