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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With