1

Very trivial question

I'm trying to understand inheritance in javascript

function Animal() {
  this.eats = true;
}
function Rabbit() {
  this.jumps = true;
}
//Rabbit is-a Animal
Rabbit.prototype = Animal;  //I'm assuming this does not inherit

alert(Rabbit.prototype.eats); // returns undefined

What is the right way?

user544079
  • 16,109
  • 42
  • 115
  • 171

1 Answers1

7

This is "answered" but allow me to offer an alternative for posterity.

It's not a good idea to invoke the parent's constructor to get the parent's prototype. Doing so may have side effects; setting ids, tracking the number of instances, whatever happens inside the constructor.

You can use Parent.call() inside the Child constructor and Object.create or the polyfill to get its prototype:

function Animal () {
    this.eats = true;
}

function Rabbit (legs) {
    Animal.call(this);
    this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);

// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
                        function F () {};
                        F.prototype = Animal.prototype;
                        return new F();
                    }());

var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Brian Moore
  • 1,588
  • 1
  • 9
  • 10