Skip to content

Instantly share code, notes, and snippets.

@sdesalas
Created April 22, 2019 14:58
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 sdesalas/e362b4b9285c47d0ffffe00c2ae44e46 to your computer and use it in GitHub Desktop.
Save sdesalas/e362b4b9285c47d0ffffe00c2ae44e46 to your computer and use it in GitHub Desktop.
OO JavaScript with super() in constructor
module.exports = class Animal {
constructor(energy) {
this.energy = energy || 0;
}
move() {
if (this.energy > 0) {
console.log('moving...')
this.energy = this.energy - 10;
} else {
console.log('cannot move.. (no energy)')
}
}
eat(food) {
this.energy = this.energy + food;
}
}
const Animal = require('./Animal.js');
module.exports = class Cat extends Animal {
constructor(energy) {
super(energy)
this.sound = 'MEAAAAAAW!!!';
}
meaw() {
console.log(this.sound)
}
}
@sdesalas
Copy link
Author

sdesalas commented Apr 22, 2019

$ node
> Cat = require('./Cat')
> var miffy = new Cat(70);
> miffy.energy
70
> miffy.meaw()
MEAAAAAAW!!!
> miffy.move() 
moving...
> miffy.energy 
60

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment