8

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

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

On calling cat1.printName() I expected it to log 'cat in cat prototype' but it logged 'cat in Animal prototype'. Could someone please explain the reason to me. Thanks.

Yosvel Quintero
19.1k5 gold badges40 silver badges47 bronze badges
asked Dec 1, 2016 at 18:12

1 Answer 1

8

You are correct, but your override of the printName() function is, itself, being overridden by the next line when you reset the Cat.prototype. Simply moving the order of the code fixes the issue:

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's 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"

answered Dec 1, 2016 at 18:16
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the explanation.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.