scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
557 stars 81 forks source link

How to tell if a class is a subclass #15

Open Faleij opened 8 years ago

Faleij commented 8 years ago

@ 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
scottwrobinson commented 8 years ago

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!

robjens commented 8 years ago

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