TypeScript/JavaScript-如何获取类的超类
TypeScript / JavaScript - How to get superclass of a class?
假设我有:
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
}
相关文章:
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 理解es6-mixin超类约定
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- 获取元素类名的部分
- 如何使用jQuery在模板kendo UI中获取元素类
- 调用子类函数时调用的超类函数
- 从 Rails dom_id 方法获取 HTML 类名
- 在IE8和其他带有javascript的浏览器中获取正文类的标准解决方案是什么
- 与超类的依赖关系
- 如何在单击父类的另一个子类时获取子类的值
- 单击按钮,如何获取与类最接近的td值
- 使用regex从css文件中获取所有类(以文本形式)
- ES6类:在超级方法中获取子类的正确名称
- 如何在javascript中从超类扩充方法
- 如何在 Javascript 中获取 CSS 类属性
- javascript对象继承-子类和超类
- 调用Class.prototype=new MyClass()是否确保每次都重新实例化超类
- 获取以类名开头的所有项
- 如何获取特定类中最近的元素
- TypeScript/JavaScript-如何获取类的超类