2017-02-21 68 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

我确实希望它被继承在我的情况下(不是静态的)...是的,这就是我一直在寻找的! –

相关问题