首页 > 解决方案 > 将静态可继承属性动态添加到类

问题描述

有没有办法动态地将静态可继承属性添加到类中?

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

标签: javascripttypescript

解决方案


只是为了记录,从一个更具体的问题(归功于那里接受的答案)我正在寻找的是

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"}

推荐阅读