Search code examples
javascriptoopinheritanceprototype

Something wrong when reset the javascript constructor


I am trying to understand inheritance in javascript. I wrote a basic example to implement a simple inheritance between the parent object and a child. But I think there is something wrong when resetting the constructor.

function Mammal(){
}
function Dog(){

}
Mammal.prototype.walk = function(){
    console.log('walking..walking....');
}
Dog.prototype.bark = function(){
    console.log('wof wof!');
}

Dog.prototype = Object.create(Mammal.prototype);
Dog.prototype.constructor = Dog;
let dogInstance = new Dog();
dogInstance.walk();
dogInstance.bark();


Solution

  • I think there is something wrong when resetting the constructor.

    No, there's not.

    Your problem is that you do

    Dog.prototype = Object.create(Mammal.prototype);
    

    after having created the bark method on the old Dog.prototype object - which you are overwriting with a new, empty object. Just do it before any assignments:

    function Mammal() {
    }
    Mammal.prototype.walk = function(){
        console.log('walking..walking....');
    };
    
    function Dog() {
    }
    Dog.prototype = Object.create(Mammal.prototype); // do this before creating properties
    Dog.prototype.constructor = Dog;
    Dog.prototype.bark = function() {
        console.log('wof wof!');
    };