0

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)?

Roman Roman
  • 617
  • 1
  • 9
  • 16

2 Answers2

3

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.

lumio
  • 7,428
  • 4
  • 40
  • 56
  • Oh, it's so easy, thanks. But when i set Dog.prototype to Animal.prototype i can access methods but can't access properties from Animal. – Roman Roman Jul 02 '17 at 17:20
  • Or i shouldn't access them? I should call getters and setters, right? – Roman Roman Jul 02 '17 at 17:22
  • Well - I would use the extend variant. It is still common practice. But of course: it depends on what you are doing – lumio Jul 02 '17 at 17:27
1

You could define Animal as a function and use its constructor to set an instance of it in the Dog prototype :

Dog.prototype = new Animal();    

More complete code :

var Animal = function () {    
   this.age = 0;
   this.weight = 0;

    this.age = function () {
        return this.age;
    }
    // define other methods ...    
    // ...
    return this;
};

var Dog = function () {           
    // overriding the age 
    this.age= 10;    
    // define or override methods ...    
    // ...
    return this;
};

// Dog extends animal
Dog.prototype = new Animal();    

// Creating an instance of Dog.
var dog = new Dog();
davidxxx
  • 125,838
  • 23
  • 214
  • 215