PrototypeJS adds better OO support

Nov 08, 2007

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!

Hi, I'm Glenn! 👋 I've spent most of my career working with or at startups. I'm currently the Director of Product @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.