如何知道JavaScript/ES6中给定类的祖先类 [英] How to know the ancestor-classes of a given class in JavaScript/ES6
本文介绍了如何知道JavaScript/ES6中给定类的祖先类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var A = class A {};
var B = class B extends A {};
var C = class C extends B {};
鉴于上面的代码假设我只能访问"C"类,我怎么知道它的祖先类是什么?正确的答案当然是B然后是A,但是我的代码如何告诉我呢?
Given the code above assuming I only have access to class 'C', how can I know what are its ancestor classes? The correct answer of course is B then A, but how can my code tell me that?
推荐答案
您可以迭代C.prototype
的原型链并获取原型的constructor
属性.
You can iterate the prototype chain of C.prototype
and get the prototype's constructor
property.
var A = class A {};
var B = class B extends A {};
var C = class C extends B {};
var proto = C.prototype;
while (proto !== Object.prototype) {
console.log(proto.constructor.name, proto.constructor);
proto = Object.getPrototypeOf(proto);
}
这篇关于如何知道JavaScript/ES6中给定类的祖先类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文