Javascript 向类动态添加静态可继承属性

Javascript 向类动态添加静态可继承属性,javascript,typescript,Javascript,Typescript,有没有一种方法可以动态地向类添加静态可继承属性 (我的具体案例是在Typescript中对我想要在类中记录并在子类中可访问的属性进行注释,但我认为这个问题也适用于javascript)只是为了记录,从一个更具体的角度来看(这是公认的答案),我想要的是 class BaseClass{} let obj = new BaseClass(); let proto = Object.getPrototypeOf(obj); Object.defineProperty(proto, "meta

有没有一种方法可以动态地向类添加静态可继承属性


(我的具体案例是在Typescript中对我想要在类中记录并在子类中可访问的属性进行注释,但我认为这个问题也适用于javascript)

只是为了记录,从一个更具体的角度来看(这是公认的答案),我想要的是

class BaseClass{}
let obj = new BaseClass();
let proto = Object.getPrototypeOf(obj);
Object.defineProperty(proto, "metaProperty", {
    enumerable: false, 
    writable: true      // important in order to set the metaProperty
});
proto.metaProperty = {a: 1, b: "hello"};     // Class BaseClass will have this proterty accessible in the prototype of all its instances (including derived ones)
class DerivedClass extends BaseClass{}
let derived = new DerivedClass();
let theProp = Object.getPrototypeOf(derived).metaProperty;  // {a: 1, b: "hello"}

如果某个“静态”的东西可以是“动态”的,我很伤心。静态属性由类的所有实例共享,不属于任何实例->您要在哪里添加新属性?很难想象)也许你有一些代码样本?@AndrewEvt是的,我看到这个问题太笼统了,需要更多的具体说明。我将删除这个问题,并创建另一个具有特定问题的问题。最后,我没有删除,因为我在另一个问题中得到了解决方案(请参见下面的答案)