Glenn Gillen

PrototypeJS adds better OO support

The folks over at prototype have had their latest 1.6 release in beta for a while, and I was using it quite extensively with much joy at my last client. One of the major enhancements to the entire system has been the reworking of the Element and Object classes, and the underlying Class object.

Previously there was all kinds of nastiness when trying to define a custom class. Here's an example taken from the docs:

var Person = Class.create();
Person.prototype = {
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
};

var guy = new Person('Miro');
guy.say('hi');
// -> "Miro: hi" 

var Pirate = Class.create();
// inherit from Person class:
Pirate.prototype = Object.extend(new Person(), {
  // redefine the speak method
  say: function(message) {
    return this.name + ': ' + message + ', yarr!';
  }
});

var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

But now with the improved Class constructor much of that heavy lifting can be put straight into the Class.create(). Then Pirate can be defined with something that looks more akin to proper object inheritance as opposed to extending the object. The end result is cleaner and more readable code:

// properties are directly passed to `create` method
var Person = Class.create({
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
});

// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
  // redefine the speak method
  say: function($super, message) {
    return $super(message) + ', yarr!';
  }
});

var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

This is just one of the many improvements in the API, some of the others are equally outstanding. I can't recommend enough the 1.6 release and I've had no problems with it, so checkout the release notes and get cracking with it today!

Glenn Gillen

I'm an advisor to, and investor in, early-stage tech startups. Beyond that I'm an incredibly fortunate husband and father. Working on a developer-facing tool or service? Thinking about starting one? Email me and let me know or come to one of our days to help make it a reality.