本文介绍了如何在运行时获取父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在运行时获取 TypeScript 类的父类?我的意思是,例如,在装饰器中:
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) {
return function (target: Function) {
var parentTarget = ?
}
}
我的自定义装饰器是这样应用的:
My custom decorator is applied this way:
export class AbstractClass {
(...)
}
@CustomDecorator({
(...)
})
export class SubClass extends AbstractClass {
(...)
}
在装饰器中,我想要一个 AbstractClass
的实例.
Within the decorator, I would like to have an instance to AbstractClass
.
非常感谢您的帮助!
推荐答案
您可以使用 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 {}
编辑
代码后@DavidSherret 补充说(在评论中),这就是你想要的(我认为):
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;
...
}
}
或者正如@DavidSherret 指出的那样:
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 :)
}
}
这篇关于如何在运行时获取父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!