Roman Roman Roman Roman - 5 months ago 23
Javascript Question

Javascript set base object when declare methods in prototype

I read that declaring object methods in prototype is good approach because it saves memory and allows to change implementation in any time for all objects.
But what i need to do when i need to set base object for object that uses prototype method declaration?
Example:

function Animal() {
this.age = 0;
this.weight = 0;
//other properties
}

Animal.prototype = {
//some methods for Animal
}


function Dog() {
//properties for Dog
}

Dog.prototype = {
//some methods for Dog
}


So, how can i set Animal as a base class(object) for Dog(because prototype property in Dog is implemented as custom object for methods)?

Answer Source

ES5 version (still most common, but I wouldn't recommend it - see ES6 version)

Based on this post here you need to use Object.create like this:

function Animal() {}
Animal.prototype = {};

function Dog() {}
Dog.prototype = Object.create( Animal.prototype );

Also see this solution with Object.assign (sadly IE doesn't support it)

ES6 version

class Animal {
  // all your methods come in here. No more prototype needed.
}

class Dog extends Animal {

}

You can already use ES6 even though most browsers don't completely support it yet. Use babel to transpile you JS.