2016-08-24 36 views
1

我想使用ES6類的靜態類屬性(0級),像這樣 -ES6等效於以下模式?

class Button { 
    static size = { 
    SMALL: "SMALL", 
    BIG: "BIG" 
    } 
} 

class UILibrary { 
    consturctor() { 
    this.button = new Button(); 
    } 
} 

// I can't access static properties of a class instance :(
const LibraryA = new UILibrary(); 
console.log(LibraryA.button.size.SMALL); 

什麼是我們的最佳選擇嗎?

EDIT

這個問題是不是在其中在階段0已經支持ES6/7,創建類屬性也沒有有關創建的靜態方法。我只是想找到一個模式,允許將類枚舉對象附加到類實例。因此沒有重複的問題建議是有效的。

+1

'我不明白爲什麼' - java和javascript是完全不相關的語言 –

+2

https://esdiscuss.org/topic/define-static-properties-and-prototype-properties-with-the-class-syntax –

+0

@JaromandaX哈哈,這是真的。但是我想從最佳實踐的角度來看,是否有這樣做的理由。 –

回答

3

我不能訪問類的實例:(

是靜態性質,如果是靜態屬性,那麼你需要訪問它們的構造:

console.log(Button.size.SMALL); 
console.log(LibraryA.button.constructor.size.SMALL); 

(見here討論的差異)

我只是想找到一個模式t帽子允許將類枚舉對象附加到類實例。

如果你想他們是可在的情況下,只是不要讓他們static

class Button { 
    // without the experimental syntax, do the assignment in the constructor 
    size = { 
    SMALL: "SMALL", 
    BIG: "BIG" 
    } 
} 

或者,而不是丟棄的static關鍵字,只是把他們的原型,以便將對象不重建一遍又一遍:

class Button {} 
Button.prototype.size = { 
    SMALL: "SMALL", 
    BIG: "BIG" 
}; 

或者,也許你不應該把他們的枚舉的類在所有的,只是使用ES6模塊的命名出口。

+0

感謝您的詳細解答。原型替代看起來很有趣。它是否有任何性能點擊? –

+0

@ user3210476:不,它實際上比第二個sinppet佔用更少的內存。原型屬性和自身屬性之間查找時間的差異很難衡量,並且取決於引擎優化。 – Bergi