samedi 2 juillet 2016

DRY JavaScript Inheritance from Within a Constructor

Is it possible to get Dog and Cat to inherit from Animal (without using the class or extends keywords), without editing the code that has already been written, and while keeping all new code within the current constructor functions?

function Animal() {
  this.sleep = function() {
    var hoursSleepPerNight = this.hoursSleepPerNight;
    console.log( "z".repeat(hoursSleepPerNight) );
  }
}

function Dog() {
  this.hoursSleepPerNight = 8;
}

function Cat() {
  this.hoursSleepPerNight = 7;
}

var dog = new Dog();
var dog.sleep;
// "zzzzzzzz"

Aucun commentaire:

Enregistrer un commentaire