Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I inherit the prototype of the Animal class in my javascript code?

Tags:

javascript

I am trying to create a new class Dog that inherits via prototypical inheritance from the Animal class:

function Animal() {
  this.name = "animal";
  this.writeName = function() {
    document.write(this.name);
  }    
}

function Dog() {
  this.name = "dog";
  this.prototype = new Animal();
}

new Dog().writeName()

​ JS Fiddle

However, I get a Javascript error: Uncaught TypeError: Object #<Dog> has no method 'say'.

Why? Shouldn't the Dog object retain an Animal object as a prototype?

like image 811
John Hoffman Avatar asked Jun 30 '12 01:06

John Hoffman


1 Answers

function Animal() {
  this.name = "animal";
  this.writeName = function() {
    document.write(this.name);
  }    
}

function Dog() {
  this.name = "dog";

}
Dog.prototype = new Animal();
dog = new Dog();
dog.writeName();

now dog has all of the properties of animal.

jsfiddle

like image 170
Ryan Avatar answered Oct 12 '22 07:10

Ryan