javascript - 将静态可继承属性动态添加到类
问题描述
有没有办法动态地将静态可继承属性添加到类中?
(我的具体情况是在 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"}
推荐阅读
- python - 将 timedelta 的时间转换/使用为 datetime
- python - try/except 子句和数值范围条件
- spring - 代理 Vaadin Spring Boot 应用程序和 URL 问题
- swift - 这是 UITextView 透明度错误吗?
- android - 如何将图标添加到 android:drawable 文件夹中?
- angular - Validators.email 指令无法正常工作
- angular - 视频结束时,HTML5 视频“结束”事件有时不会触发
- c# - 为什么我的 ASP.NET 核心应用程序仅在 PUT 调用时中断?
- python - 在python中提取每行的话语
- javascript - 如何检测画布内的元素?