Trajanson
Trajanson

Reputation: 441

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"

Upvotes: 1

Views: 97

Answers (2)

lucasjackson
lucasjackson

Reputation: 1525

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();
}

Upvotes: 2

Bergi
Bergi

Reputation: 664650

No, it is not possible (and not sensible) to keep all inheritance-related code inside the constructor if you are looking for prototypical inheritance.

Upvotes: 2

Related Questions