JavaScript prototype conversion

I am new to learning JavaScript concepts. Want to understand how prototype inheritance works. My impression was that if your class inherits a parent and you have the same method in the prototypes of both classes, when you call the method on the child instance, the method in the child prototype will be called.

the code:

function Animal(name) { this.name = name; } Animal.prototype.printName = function () { console.log(this.name + ' in animal prototype'); } function Cat(name) { Animal.call(this, name); } Cat.prototype.printName = function () { console.log(this.name + ' in cat prototype'); } Cat.prototype = Object.create(Animal.prototype); var anm1 = new Animal('mr cupcake'); anm1.printName(); var cat1 = new Cat('cat'); cat1.printName(); 

When calling cat1.printName (), I expected him to run "cat in cat prototype", but he registered "cat in Animal prototype". Maybe someone will explain the reason to me. Thanks.

+7
javascript prototype
source share
1 answer

You're right, but your overriding of printName() is itself overridden by the next line when you reset Cat.prototype . Just moving the code order fixes the problem:

 function Animal(name) { this.name = name; } Animal.prototype.printName = function() { console.log(this.name + ' in animal prototype'); } function Cat(name) { Animal.call(this, name); } // OLD LOCATION of code // This was overriding your override! // Setting the prototype of an object to another object // is the basis for JavaScript prototypical inhertiance // This line replaces the existing prototype object (which is // where your override was) with a completely new object. Cat.prototype = Object.create(Animal.prototype); // NEW LOCATION // AFTER setting the prototype (and creating inheritance), // it is safe to do the override: Cat.prototype.printName = function() { console.log(this.name + ' in cat prototype'); } var anm1 = new Animal('mr cupcake'); anm1.printName(); // "mr cupcake in animal prototype" var cat1 = new Cat('cat'); cat1.printName(); // "cat in cat prototype" 
+7
source share

All Articles