Constructor Chaining in Prototype

Ever wonder how to do constructor chaining in prototype.js?
Here's how:

var Person = Class.create({

  initialize: function(){
    console.log('hello world!');
var Pirate = Class.create(Person,{
  initialize: function($super){
    console.log('before super');
    console.log('after super');
new Person();
new Pirate();

The $super parameter is "special", and is detected by the library. It gives you a reference to the method of the same name defined in the super class(Ruby style, basically). Notice that unlike Java, you can do stuff before super's constructor is called. For more, see here.

blog comments powered by Disqus