1
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?

Panu Logic
  • 2,193
  • 1
  • 17
  • 21
  • Ok I found one way. But is there any simpler way perhaps? (C.prototype . __proto__ .constructor.prototype.__proto__.constructor === A); – Panu Logic May 23 '17 at 21:53
  • Bergi wrote: "This question has been asked before ..." . The earlier existing question was titled "Get parent class name from child with ES6?" My question was not about how to find the NAME of the parent-class, but how to find the parent-class itself, actually all ancestor-classes. Not their NAMES. I don't care at all about their names. So while the answers to the earlier question might answer also my question, these are clearly not duplicate questions. – Panu Logic May 23 '17 at 23:28

1 Answers1

3

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);
} 
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143