Announcement: JS.Class

After mentioning Prototype’s inheritance model the other day, one rather important thing struck me about it. I was going to borrow their model for some of my own work when I realised that, if you use Prototype’s $super feature, your code will break if you compress it using a variable-shrinking algorithm (all the decent compressors do this). Prototype inspects the argument names of your functions and determines whether to use Function#wrap to pass in a reference to the overridden function.

So, what to do? We use YUI at work, but their inheritance model is so cumbersome as to be almost totally useless. I needed something better. Taking a few leaves out of Prototype’s model, and out of Alex Arnell’s Inheritance.js, I’ve come up with something that does just what I want. Basic features:

  • Simple, elegant single-inheritance model, including inheritance of class (static) methods
  • Clean, intuitive access to the class hierarchy from within instance methods, as well as through class interfaces
  • Automated inheritance: adding class/instance methods to a class after its initial definition instantly updates all its subclasses and their instances
  • Mixins, like in Ruby (this is essentially Ruby-ish syntax masking a trivial JavaScript feature)
  • super, with arguments optional
  • is_a support (JavaScript trivially supports has-a relationships itself)

Although this takes much of its syntax ideas from Ruby (that being the classical inheriting language I know best), it should be intelligeable to users of other classical OO languages such as Java (we are a Java shop where I work).

So, without further ado, go check out JS.Class.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.