i don\'t get why everyone is using Boy.prototype = new Human;
to simulate inheritance. Look, what we want is the function\'s of A right? we can do that without
A better option is to create an intermediate to hold the prototype.
function extend(clazz, superclass) {
var intermediate = function() {};
intermediate.prototype = superclass.prototype;
clazz.prototype = new intermediate();
// Following line is optional, but useful
clazz.prototype.constructor = clazz;
}
This avoids unnecessary copying, but still means that you don't need to instantiate an object that will do work in its constructor. It also sets up the prototype chain so that you can use instanceof. It also doesn't result in superclass prototype contamination which some inheritance antipatterns can.
For completeness, your subclass should call the superclass constructor in its constructor, which you can do with Superclass.call(this);
.
EDIT: Since ES5, you can replace calls to extend
with
Subclass.prototype = Object.create(Superclass.prototype);
which does the same thing.