Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Created May 19, 2017 20:16
Show Gist options
  • Save bluepnume/7c6128ba197d8eac00e94c4af39cbc98 to your computer and use it in GitHub Desktop.
Save bluepnume/7c6128ba197d8eac00e94c4af39cbc98 to your computer and use it in GitHub Desktop.
// Register a pair of ES6 classes called "Animal" and "Cat" *without* inheritance, so I can do:
var animal = new Animal();
animal.walk(); // logs 'The Animal walked'
var cat = new Cat();
cat.walk(); // logs 'The Cat walked'
cat.meow(); // logs 'The Cat meowed'
console.log(cat instanceof Cat); // logs true
console.log(cat instanceof Animal); // logs false
// Note: I should only implement the logic in the *walk* function a single time, and use composition to let it be called from Cat
@wildlingjill
Copy link

// Register a pair of ES6 classes called "Animal" and "Cat" with inheritance, 
// so I can do:

class Animal {
  constructor() {
    this.name = "Animal";
  }
  
  walk() {
    console.log("The " + this.name + " walked");
  }
}

class Cat extends Animal {
  constructor () {
    super()
    this.name = "Cat";
  }
  
  meow() {
    console.log("The " + this.name + " meowed");
  }
}


var animal = new Animal();
animal.walk(); // logs 'The Animal walked'

var cat = new Cat();
cat.walk(); // logs 'The Cat walked'
cat.meow(); // logs 'The Cat meowed'
console.log(cat instanceof Cat); // logs true
console.log(cat instanceof Animal); // logs true

// Do the same using pure ES5 contructors (no ES6 classes)

function Animal () {
  this.name = "Animal";
}

Animal.prototype.walk = function(){
  console.log("The " + this.name + " walked");
}


function Cat () {
  this.name = "Cat";
}

// this is inheritance, makes cat a new subclass of animal
// use either inheritance or composition (below)
Cat.prototype = new Animal();

Cat.prototype.meow = function() {
  console.log("The " + this.name + " meowed");
}

// this is composition rather than inheritance as just calling another method
// can pick and choose which functions you want rather than just getting all of them
Cat.prototype.walk = function() {
  Animal.prototype.walk();
}



var animal = new Animal();
animal.walk(); // logs 'The Animal walked'

var cat = new Cat();
cat.walk(); // logs 'The Cat walked'
cat.meow(); // logs 'The Cat meowed'
console.log(cat instanceof Cat); // logs true
console.log(cat instanceof Animal); // logs true

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