How to get the parent class at runtime

后端 未结 1 409
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 17:46

Is it possible to get the parent class of a TypeScript class at runtime? I mean, for example, within a decorator:

export function CustomDecorator(data: any)          


        
相关标签:
1条回答
  • 2020-12-17 18:16

    You can use the Object.getPrototypeOf function.

    Something like:

    class A {
        constructor() {}
    }
    
    class B extends A {
        constructor() {
            super();
        }
    }
    
    class C extends B {
        constructor() {
            super();
        }
    }
    
    var a = new A();
    var b = new B();
    var c = new C();
    
    Object.getPrototypeOf(a); // returns Object {}
    Object.getPrototypeOf(b); // returns A {}
    Object.getPrototypeOf(c); // returns B {}
    

    Edit

    After the code @DavidSherret added (in a comment), here's what you want (I think):

    export function CustomDecorator(data: any) {
      return function (target: Function) {
        var parentTarget = target.prototype;
        ...
      }
    }
    

    Or as @DavidSherret noted:

    function CustomDecorator(data: any) {
      return function (target: Function) {
        console.log(Object.getPrototypeOf(new (target as any)));
      }
    }
    

    2nd Edit

    Ok, so here's what I hope to be you goal:

    function CustomDecorator(data: any) {
        return function (target: Function) {
            var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
            console.log(parentTarget === AbstractClass); // true :)
        }
    }
    
    0 讨论(0)
提交回复
热议问题