2017-12-18 236 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