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

I am trying to create a new class Dogthat inherits through prototype class inheritance Animal:

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 feed

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

Why? Should the object Dogsave the object Animalas a prototype?

+5
source share
3 answers
Of course, the correct answer is correct, but it really does not say what is different about this, and this may not be clear to beginners, so ...

, , , this.prototype = new Animal(); Animal prototype Dog ( this), prototype .

prototype . SomeFunc new SomeFunc(), internal/hidden [[prototype]] , SomeFunc.prototype. prototype .

+3
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();

.

jsfiddle

+7

"prototype" . [[Proto]], , ( : Firefox, __proto__).

Javascript, , , Object.create [[Prototype]]:

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

function Dog() {
  var dog = Object.create(new Animal())
  dog.name = "dog";
  return dog;
}

(new Dog()).writeName()

- , Object.create new Animal , , , .

+2

All Articles