TypeScript/JavaScript-如何获取类的超类

TypeScript / JavaScript - How to get superclass of a class?

本文关键字:获取 超类 JavaScript- 何获取 TypeScript      更新时间:2023-09-26

假设我有:

class Foo {}
class Bar extends Foo {}
var clazz = Bar;

我发现要得到Bar,就有clazz.prototype.constructor

如何查找Bar的父类?

正如@MattiasBuelens对答案的评论,它应该是:obj.constructor而不是obj.prototype.constructor,因为obj.prototype为null(prototype属性存在于类Bar上,但不存在于实例上)。

至于获得Foo的构造函数,这是一个丑陋的破解:

let FooCtor = Object.getPrototypeOf(Object.getPrototypeOf(obj)).constructor;
var foo = new FooCtor();

编辑

如果您想做同样的事情,但使用Bar类而不是它的实例,那么:

let FooCtor = Object.getPrototypeOf(Bar.prototype).constructor;
var foo = new FooCtor();

TypeScript 1.8使用它来扩展类(为了可读性,此处减少):

var __extends = function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = (__.prototype = b.prototype, new __());
};
var TestPlanetModel = (function (_super) {
    __extends(TestPlanetModel, _super);
    function TestPlanetModel() {
        _super.apply(this, arguments);
    }
    return TestPlanetModel;
}(FrameModel));

它使用本地Function来实例化原型,并在该闭包中隐藏两个类之间的关系。

感谢Nitzan的技巧,我只需要检查类,而不是对象,所以我实例化它以获得原型:

var clazz = TestPlanetModel;
var parent = Object.getPrototypeOf(Object.getPrototypeOf(new clazz())).constructor;
alert(parent === FrameModel);

我不知道如何在不实例化的情况下完成它。

我最近发布了TypeScript编译器的增强版,它可以让您在编码时和运行时了解类和接口的所有反射元数据。以下代码适合您的需求:

class MySuper {
    id: number;
    constructor(n: number) {
        console.log("MySuper instantiated with param: " + n);
        this.id = n;
    }
}
class MySub extends MySuper {
    name: string;
}

let sub: Class = MySub.getClass();
if(sub.extends) {
    let superCtor = sub.extends.getConstructor<MySuper>(); //type param is optional, you can get "any" by default.
    //let's instantiate it!!!
    let superObj = new superCtor(3);
    console.log("superObj.id = " + superObj.id);
}

这是输出:

$ node main.js
MySuper instantiated with param: 3
superObj.id = 3

你可以在这里找到我的项目。

您可以使用;Object.getPrototypeOf(AnyClass)";返回AnyClass:的超类

 class Foo {}
 class Bar extends Foo {};
 let SuperClassOfBar = Object.getPrototypeOf (Bar);
 if (SuperClassOfBar === Foo)
 { console.log 
    (`Superclass of Bar is Foo`);  // yes it is
 }