在原型中声明 TypeScript 成员而不是添加到 'this'

Declaring TypeScript member in prototype rather than adding to 'this'

以下打字稿:

class A {
    member = "value";
}

...编译为:

var A = (function () {
    function A() {
        this.member = "value";
    }
    return A;
})();

我想实现以下目标:

var A = (function () {
    function A() {
    }

    A.prototype.member = "value";

    return A;
})();

这样做的原因是我相信后一种构造可能更有效,因为 (1) 赋值 this.member = "value" 语句不必在每次创建新实例时都执行,并且 (2 ) 实例内存负载会更小。

免责声明:我没有对这两个构造进行基准测试,所以我真的不知道情况是否如此。

所以我的问题是:是否可以使用类型脚本声明 "prototype member"?

如果有人能解释 为什么类型脚本是这样设计的,我也很高兴?。 (参见 §8.4.1 in the specification

我知道以这种方式声明可变成员是愚蠢的,但是不可变基元的声明,如 stringnumber,应该可以在原型上设置,对吧?

可能的解决方法是:

class A {
    member: string;
}

A.prototype.member = "value";

但是,这不适用于私人会员:

class A {
    private member: string;
}

A.prototype.member = "value"; // error TS2107: 'A.member' is inaccessible.

Is it possible to declare a "prototype member" using type script?

不,语言目前不允许这样做。

解决方法

当编译器不高兴时...断言:

class A {
    private member: string;
}

(<any>A.prototype).member = "value"; // suppressed

why type script is designed this way

仅仅是因为在 prototype 上有 非函数 是非惯用的。

(1) the assignment this.member = "value" statement would not have to be executed every time a new instance is created, and (2) instance memory payload would be smaller.

但是查找肯定会慢一些。这是一个示例测试:http://jsperf.com/prototype-vs-this-access

我想出了一个也适用于私有成员的可行解决方法:

class A {
    private member: string;

    static __init = (() => {
        A.prototype.member = "value";
    })();
}

这很不错;所有代码都在 class 构造中,我避免转换为 any 因此仍然可以跟踪对那些私有成员的引用(用于重构等)。

使用此方法时,在 class 函数上声明了一个虚拟 __init 成员。不过问题不大。