javascript - Javascript:在父类的构造函数中访问子类的元数据
问题描述
我想在超级调用之前访问其父构造函数中子类的元数据。
请参见以下示例:
import "reflect-metadata";
const KEY = Symbol()
function Decorator(name: string) {
return function(target: any) {
Reflect.defineMetadata(KEY, name, target);
}
}
class BaseBase {
constructor(name: string) {
console.log(name);
}
}
class Base extends BaseBase {
constructor() {
// prints "undefined" (because its defined on the Child constructor)
console.log(Reflect.getMetadata(KEY, Base));
console.log(Reflect.getMetadata(KEY, arguments.callee)); // ERROR: deprecated and removed in ES5
super("insert meta data here");
// will print "ChildName" but this can not be used before super call
console.log(Reflect.getMetadata(KEY, Reflect.getPrototypeOf(this).constructor));
console.log(Reflect.getMetadata(KEY, this.constructor));
}
}
@Decorator("ChildName")
class Child extends Base {}
new Child();
有没有办法将Child
类的元数据传递给BaseBase
类?
我想我可以访问Child
构造函数中的元数据并将其传递给构造函数调用Base
,但是我有许多不同的 Childs,我想避免为所有它们定义一个构造函数。
解决方案
推荐阅读
- python - 不同服务器之间的 pg_dump 和 pg_restore 对要转储的数据具有选择标准
- java - HashMap:有没有办法通过哈希码而不是按键进行搜索?
- highcharts - HighCharts:不出现多个 X 和 Y 轴工具提示(自定义格式化程序)
- ffmpeg - AVFormatContext:中断回调正确用法?
- r - R中的前高斯包?
- graphql - GraphQL Apollo 解析器没有触发?
- python - 同时运行main函数和receive函数
- python - Udacity - 烧瓶 Python
- swift - SwiftUI List 和 For Each 循环与空白元素
- javascript - 上传包含子文件夹的文件夹并保留它们?