Vic Cat o'Lick
Vic Cat o'Lick

Reputation: 13

Javascript - Calling a child method from inside a prototype method

Is it possible to call a regular method from a prototype method if it's been overridden? Note that in the given example the first eat() method is called from the body of the Animal function - it is the requirement.

Animal = function(){
    this.eat();
};

Animal.prototype.eat = function() {
    console.log("All animals eat");
};

Bear = function(){
    Animal.call(this);
    this.goToSleep = function(){
        console.log("Bears go to sleep after they eat");
    }
};

Bear.prototype = Object.create(Animal.prototype);

Bear.prototype.eat = function() {
    console.log("Bears eat honey");
    this.goToSleep(); //returns 'undefined is not a function'
    //How do I invoke this.goToSleep() ?
};

var winnie = new Bear();

Upvotes: 1

Views: 78

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159875

The issue is that your bear doesn't have a goToSleep method when eat first gets invoked.

When you invoke Animal.call(this) in your Bear constructor it then calls eat - which is found on Bear.prototype and invoked. Then eat tries to invoke goToSleep but goToSleep is an instance method that you haven't added yet (remember, we are still on Animal.call we haven't reached this.goToSleep = function() yet).

Unless you have a good reason to, goToSleep should be a prototype method as well, just like eat:

Bear.prototype.goToSleep = function(){
  console.log("Bears go to sleep after they eat");
};

This will just work as you want it to.

Alternatively, if goToSleep has to be an instance method (because it needs access to some private state you create in your constructor), then simply switch the order of your Animal.call and this.goToSleep lines:

this.goToSleep = function() // etc.
Animal.call(this);

Upvotes: 1

Related Questions