camo icon indicating copy to clipboard operation
camo copied to clipboard

How to tell if a class is a subclass

Open Faleij opened this issue 9 years ago • 2 comments

@ lib/document.js:31 // TODO: Is there a way to tell if a class is // a subclass of something? Until I find out // how, we'll be lazy use this.

If you need to get the subclass of an instance in a parent method - just use Object.getPrototypeOf(this).constructor

'use strict';

class A {
  getSubclass() {
    return Object.getPrototypeOf(this).constructor;
  }

  isSubclass() {
    return Object.getPrototypeOf(this).constructor !== A;
  }
}
class B extends A {}
class C extends B {}

// Static usage:
console.log(Object.getPrototypeOf(C).name); // B
// To get top parent you need to traverse the prototype chain:
console.log(Object.getPrototypeOf(Object.getPrototypeOf(C)).name); // A

// Instance usage:
let c = new C();
let a = new A();

console.log(c.getSubclass().name); // C
console.log(c.isSubclass()); // true
console.log(a.isSubclass()); // false

Faleij avatar Nov 14 '15 16:11 Faleij

Ah yes, that's a much better solution than what is currently in there. I'll have to include that in the next update. Thanks for pointing that out!

scottwrobinson avatar Nov 23 '15 17:11 scottwrobinson

Note the slightly different syntax for either retrieving base or derived type using the above method, e.g.

class A { }

const B = class B extends A {
  get type () {
    return {
      self: Object.getPrototypeOf (this.constructor).name, // B
      base: Object.getPrototypeOf (this).constructor.name // A
    }
  }
}

robjens avatar Mar 18 '16 23:03 robjens