Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
javamonkey79 Avatar asked Dec 16 '22 08:12

javamonkey79


2 Answers

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(); }
like image 136
NullUserException Avatar answered Jan 01 '23 17:01

NullUserException


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); }
  1. You should define method woof as the property of the Dog's prototype.
  2. _super is available only as the property of the Dog constructor.
  3. You should call the methods of the parent class in context of the current instance.
like image 28
bjornd Avatar answered Jan 01 '23 17:01

bjornd