2017-02-21 67 views
0

當我使用字符串字段創建類時,它總是在構造函數中轉換爲賦值。是否有可能使它在原型上,以便它被共享而不是每個實例的新字符串?如何在TypeScript的類的原型上創建字符串

class A { 
    a = 'hello' 
    b() { return this.a;} 
} 
// Transpiles into 
var A = (function() { 
    function A() { 
     this.a = 'hello'; 
    } 
    A.prototype.b = function() { return this.a; }; 
    return A; 
}()); 
// Is it possible to make it go on the prototype like functions do? 
// No need for multiple instances of the string 
var A = (function() { 
    function A() {} 
    A.prototype.b = function() { return this.a; }; 
    A.prototype.a = 'hello'; 
    return A; 
}()); 

回答

4

是的,這是可能的,而且它可能更直截了當,你想象......

class A { 
    public foo: string; 
} 
A.prototype.foo = 'im shared between instances'; 

如果您有興趣的理由爲什麼沒有特別的關鍵字來定義一個「原型成員'在課堂定義裏面,你可以閱讀更多關於它的信息here。尋找來自ahejlsberg(Anders Hejlsberg)的評論。

您也可以使變量static,在這種情況下,它將存儲在構造函數\ class中。

+0

我確實希望它被繼承在我的情況下(不是靜態的)...是的,這就是我一直在尋找的! –

相關問題