如何在运行时获取父类

Thi*_*ier 9 typescript

是否有可能在运行时获取TypeScript类的父类?我的意思是,例如,在装饰者中:

export function CustomDecorator(data: any) {
  return function (target: Function) {
    var parentTarget = ?
  }
}
Run Code Online (Sandbox Code Playgroud)

我的自定义装饰器以这种方式应用:

export class AbstractClass {
  (...)
}

@CustomDecorator({
  (...)
})
export class SubClass extends AbstractClass {
  (...)
}
Run Code Online (Sandbox Code Playgroud)

在装饰器中,我想有一个实例AbstractClass.

非常感谢您的帮助!

Nit*_*mer 9

您可以使用Object.getPrototypeOf函数.

就像是:

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 {}
Run Code Online (Sandbox Code Playgroud)

编辑

代码 @DavidSherret添加(在评论中),这是你想要的(我认为):

export function CustomDecorator(data: any) {
  return function (target: Function) {
    var parentTarget = target.prototype;
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

或者@DavidSherret指出:

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

第二次编辑

好的,所以这就是我希望成为你的目标:

function CustomDecorator(data: any) {
    return function (target: Function) {
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        console.log(parentTarget === AbstractClass); // true :)
    }
}
Run Code Online (Sandbox Code Playgroud)