Trajanson Trajanson - 5 months ago 8
Javascript Question

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();
dog.sleep();
// "zzzzzzzz"

Answer

Javascript uses prototypal inheritance, so you can inherit from Animal as follows:

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

function Dog() {
  this.hoursSleepPerNight = 8;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

function Cat() {
  this.hoursSleepPerNight = 7;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

var dog = new Dog();
dog.sleep();

Here is a fiddle: https://jsfiddle.net/k0op9sb6/

If for some reason you must set the prototype within the constructor functions it looks like you may be able to use Object.setPrototypeOf or __proto__ (proto) -- HOWEVER this is universally NOT RECOMMENDED:

function Dog() {
  this.hoursSleepPerNight = 8;
  Object.setPrototypeOf(this, new Animal()); // this.__proto__ = new Animal();
}