Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Created February 26, 2020 17:43
Show Gist options
  • Save munkacsitomi/4c51b3b0d9ee32ee6c5f10a135469b4e to your computer and use it in GitHub Desktop.
Save munkacsitomi/4c51b3b0d9ee32ee6c5f10a135469b4e to your computer and use it in GitHub Desktop.
ES6 Class inheritance example
class Person {
constructor(name) {
this.name = name;
}
dance() {
return true;
}
}
class Ninja extends Person {
constructor(name, weapon) {
super(name);
this.weapon = weapon;
}
wieldWeapon() {
return true;
}
}
const person = new Person('Bob');
console.log(person instanceof Person, 'A person’s a person');
console.log(person.dance(), 'A person can dance.');
console.log(person.name === 'Bob', 'We can call it by name.');
console.log(!(person instanceof Ninja), 'But it’s not a Ninja');
console.log(typeof person.wieldWeapon === 'undefined', 'And it cannot wield a weapon');
const ninja = new Ninja('Yoshi', 'Wakizashi');
console.log(ninja instanceof Ninja, 'A ninja’s a ninja');
console.log(ninja.wieldWeapon(), 'That can wield a weapon');
console.log(ninja instanceof Person, 'But it’s also a person');
console.log(ninja.name === 'Yoshi', 'That has a name');
console.log(ninja.dance(), 'And enjoys dancing');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment