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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Or i shouldn't access them? I should call getters and setters, right?
Well - I would use the extend variant. It is still common practice. But of course: it depends on what you are doing
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.