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?
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(); }
The last string of the Dog pseudo-class definition is wrong. It should be
Dog.prototype.woof = function(){ console.log( "Woof!" ); Dog._super.speak.call(this); }
woof
as the property of the Dog
's prototype._super
is available only as the property of the Dog
constructor.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With