Search code examples
javascriptinheritanceprototypal-inheritance

Javascript prototypal inheritance weirdness


I'm trying to work through some javascript inheritance examples and I hit a wall with this one:

function Animal(){}
Animal.prototype.type = "animal";
Animal.prototype.speak = function(){ console.log( "I'm a " + this.type + 
    ". I can't really talk ;)" ); }

function Dog(){}

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

Dog.prototype = new F();
Dog.prototype.constructor = Dog;
Dog.prototype.type = "Dog";
Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }

var rover = new Dog();
rover.woof();

I am getting this and I have no idea why:

TypeError: Object #<Dog> has no method 'woof'

I know I can put the not-found method into the constructor function, but I am trying to do this with prototype modification. What am I doing wrong here?


Solution

  • Change:

    Dog._super = Animal.prototype;
    Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }
    

    To:

    // Dog.prototype._super = Animal.prototype; <- you can remove this line
    Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); }