2009-09-27

Simple JavaScript Inheritance

Here's a simple method for doing JavaScript inheritance, which doesn't rely on directly accessing __proto__ (so it should work in e.g. Internet Explorer), and heeds some important advice from Mozilla not to call ParentClass() to create ChildClass()'s prototype. It seems much simpler than the solutions proposed by Mozilla devs, here.
var extend = function(parent, child){
  var blank_constructor = function(){};
  blank_constructor.prototype = parent.prototype;
  child.prototype = new blank_constructor;
  child.prototype.__super = parent.prototype; /* so the instance of Child can call Parent functions */
};

var Parent = function(){};

Parent.prototype = {'word': 'socialism'};

var Child = function(){};

extend(Parent, Child);

var the_child = new Child;

console.log(the_child.word); // outputs "socialism"

Parent.prototype.word = 'capitalism';

console.log(the_child.word); // outputs "capitalism", proving inheritance works
Here's the point made at Mozilla's MDC:
You could inherit via:

B.prototype = new A();

But that creates an instance of A() at the time of loading the JS file. That's a very bad idea, because you may do some processing in A's constructor, which may take time and thus significantly delay the load, or try to access things (e.g. functions in your utils.js) which are not loaded yet.
Any unaddressed holes or other issues here?

No comments: