Quick Links

Current version is 2.0b. Be aware that the code and documentation may be updated at any time with bug fixes. After some more thorough testing, it will come out of beta and any further changes will be released as newer versions.

  • Download: class.zip
  • Documentation (full of examples)
  • Questions, compliments and bug reports: Send an email to jlau at uselessspickles dot com

The $class Library

Object-oriented JavaScript made easy

The $class library provides convenient syntax for defining classes and also provides many features not directly supported by JavaScript, such as interfaces, abstract classes and easily calling an overridden implementation of a method. There's even built-in support for creating singletons and miltitons.

Here's an example to whet your appetite:

$namespace("samples");

$class("samples.Person", {
  $constructor: function(name) {
    this._name = name;
  },
  
  getName: function() {
    return this._name;
  }
});

$class("samples.Officer", {
  $extends: samples.Person,
  
  $constructor: function(name, rank) {
    // call Person's constructor implementation
    this.$base(name);
    this._rank = rank;
  },
  
  getName: function() {
    // add the officer's rank to the name
    return this._rank + " " + this.$base();
  }
});

var officer = new samples.Officer("Coltraine", "Sheriff");

alert(officer.getName()); // alerts "Sheriff Coltraine"
alert(officer instanceof samples.Officer) // alerts "true"
alert(officer instanceof samples.Person) // alerts "true"
alert($class.typeOf(officer)) // alerts "samples.Officer"
alert(officer) // alerts "[object samples.Officer]"

In addition to the convenient syntax, the $class library helps you avoid spending time debugging by reporting errors for many situations, such as attempts to instantiate abstract classes, a class implementing an interface without providing all methods in the interface, and more.

But I want my code to be fast!

All that helpful error checking requires quite a bit of overhead, but it's only really necessary when developing or debugging. Luckily, the $class library is supplied in two forms: the "debug" version with all the helpful error checking, and "production" version with minimal overhead to make things work, but with absolutely no error checking. The production version even implements some optimizations, like skipping empty constructors in an inheritence chain when instantiating a class.

Tell me more!

I'll work on adding some more examples to this page, or maybe create a separate page/blog for posting examples and tips. For now, you'll just have to RTFM (it has lots of examples).