camo
camo copied to clipboard
How to tell if a class is a subclass
@ 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
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!
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
}
}
}