Javascript prototype inheritance weirdness

I am trying to work with some examples of javascript inheritance and I hit a wall with this:

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 get this and I have no idea why:

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

I know that I can put the method not found in the constructor function, but I'm trying to do this with a modification of the prototype. What am I doing wrong here?

+4
source share
4 answers

Edit:

 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(); } 
+4
source

The last line of the Dog pseudo-class definition is incorrect. It should be

 Dog.prototype.woof = function(){ console.log( "Woof!" ); Dog._super.speak.call(this); } 
  • You must define the woof method as a property of the Dog prototype.
  • _super is only available as a property of the Dog constructor.
  • You must call the methods of the parent class in the context of the current instance.
+4
source

So your woof method is actually a static method (if you use java. Basically, it hangs on the Dog function and can be accessed without an instance of Dog. Ie: Dog.woof ())

To make it work with a dog instance, you want to make sure that it is a prototype definition (again, with the analogy of Java, defining an instance method is effective). As qwertymik said,

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

Then you can do

 var foo = new Dog(); foo.woof(); 
+3
source

Perhaps you want to do this:

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

All Articles