Skip to content

Instantly share code, notes, and snippets.

@imanabu
Created March 4, 2019 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imanabu/f605fa0f72f778e135fdfb874e705647 to your computer and use it in GitHub Desktop.
Save imanabu/f605fa0f72f778e135fdfb874e705647 to your computer and use it in GitHub Desktop.
Do Not Confuse Class and Instance Inheritance With TypeScript
/**
* Combined class and instance inheritance in TypeScript
* This looks deceptively simple, but there are two layers of inheritance that's happening
* One is the Class inheritance. Another is the actual instance inheritance that's chained
* through the children array. The parent has its' instance based factory to generate its
* own children either daughters of sons
*/
class person {
constructor(name, parent = null) {
this.name = name;
this.parent = parent;
this.children = [];
// Do not instantiate subclass here. It will create a constructor loop
// Try uncommenting the line below and see what happens
// const s = new son("kyle", this);
}
create(name, kind) {
if (kind === "daughter") {
const c = new daughter(name, this);
return c;
}
if (kind == "son") {
const c = new son(name, this);
return c;
}
return;
}
show() {
return this.name;
}
toString() {
return this.name ? this.name : "nobody";
}
}
exports.person = person;
class daughter extends person {
constructor(name, parent) {
super(name, parent);
parent.children.push(this);
}
}
exports.daughter = daughter;
class son extends person {
constructor(name, parent) {
super(name, parent);
parent.children.push(this);
}
}
exports.son = son;
let p = new person("Kathy");
let d = p.create("Kim", "daughter");
let gd = d.create("Kerry", "daughter");
let s = p.create("Ken", "son");
console.log(`Parent ${p.show()} has ${p.children}`);
console.log(`Daughter ${d.show()} has ${d.children}`);
console.log(`${gd.show()}'s parent is ${gd.parent.show()}`);
console.log(`${gd.show()}'s grand parent is ${gd.parent.parent.show()}`);
console.log(`Son ${s.show()} has ${s.children.length ? s.children : "nobody"}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment