How to know the ancestor-classes of a given class

2019-07-27 03:02发布

问题:

This question already has an answer here:

  • Get parent class name from child with ES6? 4 answers
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:

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