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

javascript

Solution

@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 an `Animal` instance to a property named `prototype` on the current `Dog` instance (referred to by `this`), but there's nothing special about a property named `prototype` in this context.

The `prototype` property is only magical on function objects. When you create a new instance of `SomeFunc` using `new SomeFunc()` that new object's internal/hidden [[prototype]] pointer will refer to the object pointed to by `SomeFunc.prototype`. The `prototype` name isn't special in any other context.

Problem

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?

Original source

Related problems