首页 > 解决方案 > 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,我想避免为所有它们定义一个构造函数。

标签: javascripttypescriptdecoratorreflect

解决方案


推荐阅读