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()
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?
@ryan’s answer is correct, of course, but he doesn’t really say what’s different about it and it might not be clear to a beginner, so…
The mistake you’re making is that
this.prototype = new Animal();assigns anAnimalinstance to a property namedprototypeon the currentDoginstance (referred to bythis), but there’s nothing special about a property namedprototypein this context.The
prototypeproperty is only magical on function objects. When you create a new instance ofSomeFuncusingnew SomeFunc()that new object’s internal/hidden [[prototype]] pointer will refer to the object pointed to bySomeFunc.prototype. Theprototypename isn’t special in any other context.