获取TypeScript中的扩展类列表

时间:2016-08-08 11:41:38

标签: typescript

我有:

classA 
classB extends ClassA
classC extends ClassB

我在classC上创建了对象:

var myClassC= new classC();

ClassA有这种方法:

public get className(): string {
    var funcNameRegex = /function (.{1,})\(/;
    var results = (funcNameRegex).exec(this["constructor"].toString());
    return (results && results.length > 1) ? results[1] : "";
}

如果我调用myClassC.getClassName();

,则返回“ClassC”字符串

我需要的是获取基类的所有类的列表:ClassC,ClassB,ClassA。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:5)

是的,这确实是可能的:

function getClassName(obj: any): string {
    var funcNameRegex = /function (.{1,})\(/;
    var results = (funcNameRegex).exec(obj.constructor.toString());
    return (results && results.length > 1) ? results[1] : "";
}

class ClassA {
    public get className(): string[] {
        let classNames = [];
        let obj = Object.getPrototypeOf(this);
        let className: string;

        while ((className = getClassName(obj)) !== "Object") {
            classNames.push(className);
            obj = Object.getPrototypeOf(obj);
        }

        return classNames;
    }
}

class ClassB extends ClassA {}

class ClassC extends ClassB {}

let a = new ClassA();
console.log(a.className); // ["ClassA"]

let b = new ClassB();
console.log(b.className); // ["ClassB", "ClassA"]

let c = new ClassC();
console.log(c.className); // ["ClassC", "ClassB", "ClassA"]

code in playground