在TypeScript中定义原型属性

ie.*_*ie. 2 typescript

我有一节课,比方说A.我需要声明一个可以访问的prototype属性,如下所示:

var idKey = A.prototype.attributeId;
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码执行此操作:

class A {
  constructor() {
      A.prototype.attributeId = "InternalId";
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

Mar*_*tin 9

这并不理想,但它适合您的需求.

class A {
    attributeId:string;
}
A.prototype.attributeId = "InternalId";
Run Code Online (Sandbox Code Playgroud)

这将编译为es5:

var A = (function () {
    function A() {
    }
    return A;
})();
A.prototype.attributeId = "InternalId";
Run Code Online (Sandbox Code Playgroud)


jjr*_*jrv 6

这是另一种方法,使用装饰器:

function setProto(value: any) {
    return((target: any, key: string) => {
        target[key] = value;
    });
}

class A {
    @setProto("InternalId")
    attributeId:string;
}
Run Code Online (Sandbox Code Playgroud)

它被编译为一些粘合代码(仅定义一次)和:

var A = (function () {
    function A() {
    }
    __decorate([
        setProto("InternalId")
    ], A.prototype, "attributeId");
    return A;
})();
Run Code Online (Sandbox Code Playgroud)