0

I'm reading a tutorial about inheritance in JavaScript, and there is the following statement:

For an object of Rabbit class to inherit from Animal class we need:

  1. Define Animal
  2. Define Rabbit
  3. Inherit Rabbit from Animal:

    Rabbit.prototype = new Animal()

They say that this approach has a disadvantage of a need to create a redundant object. I don't understand why I need to create that redundant object? I've tried the following and it worked without creating redundant objects:

function Animal() {};
function Rabbit() {};
Rabbit.prototype = Animal.prototype
Animal.prototype.go = function() {alert("I'm inherited method"};
var r = new Rabbit();
r.go();

What am I missing here?

2 Answers 2

3

What you're missing is that with your code, Rabbit and Animal share the exact same prototype. If you added an eatCarrot method to Rabbit then every other Animal would have that method too.

The tutorial you're using is actually somewhat out of date. The preferred way to subclass instead is to use Object.create to create a brand new prototype object for Rabbit that chains to the Animal.prototype:

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

Note that this does not depend on subclassing the Rabbit from an instance of Animal.

See MDN for more information.

Sign up to request clarification or add additional context in comments.

Comments

3

There is a critical deficiency of your approach, best demonstrated by an example:

function Animal() {};
Animal.prototype.feed = function(){
  console.log("feeding")
};

function Rabbit() {this.teeth = 4};
Rabbit.prototype = Animal.prototype; // oops
Rabbit.prototype.feed = function(){
  if(this.teeth > 1){
    console.log("chewing")
  } else {
    throw "I have no teeth!"
  }
}

var leechworm = new Animal;
leechworm.feed(); //throws

since leechworm is an Animal, it should be able to feed no matter what kinds of animals we define, but since Animal.prototype === Rabbit.prototype, Animal.prototype.feed is the same as Rabbit.prototype.feed. The leechworm will complain about his lack of teeth.

Comments

Your Answer

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.