shilpi
shilpi

Reputation: 108

JavaScript prototype overriding

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.

Upvotes: 8

Views: 2303

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

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"

Upvotes: 8

Related Questions