How to know the ancestor-classes of a given class

2019-07-27 03:26发布

This question already has an answer here:

var A = class A {};
var B = class B extends A {};
var C = class C extends B {};

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?

1条回答
乱世女痞
2楼-- · 2019-07-27 03:57

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);
} 

查看更多
登录 后发表回答