JS.Class is a library designed to facilitate object-oriented development in JavaScript. It
implements Ruby’s core object, module and class system and some of its metaprogramming facilities,
giving you a powerful base to build well-structured OO programs.
var Event = new JS.Class({
include: JS.Observable,
fire: function(data) {
this.notifyObservers('fire', data);
}
});
Features
JS.Class is designed to make JavaScript behave like Ruby in terms of its OOP structures.
To this end, it provides the following features:
- Classes and modules with Ruby-compatible inheritance
- Subclassing and mixins
- Late-binding arguments-optional
supercalls to parent classes and mixins - Singleton methods and eigenclasses
included,extendedandinheritedhooks- Method binding
- Ports of various standard Ruby modules, including
Enumerable,Hash,Set,Observable,Comparable,Forwardable
Its inheritance system supports late-bound super() calls to parent classes and modules,
including calls from singleton methods. It has been designed to mimick Ruby as closely as
possible, so if you know Ruby you should feel right at home.
Download version 2.1
Version 2.1 builds on the 2.0 core and libraries and adds several new core features and packages. A quick tour of the new features:
- New libraries:
ConstantScope,HashandHashSet, a much fasterSetimplementation. - The package manager has been improved with a new API, parallel downloading of files, and support for server-side environments such as SpiderMonkey, Rhino and V8. It also supports user-defined loader functions for transparent integration with Google and Yahoo!’s packaging systems.
- The
Enumerablemodule has been updated with plenty of methods from Ruby 1.9, and now supports enumerators, andSymbol#to_proc-like functionality whereby a string,MethodChainor any object that implementstoFunction()can be used as an iterator. - The core object methods now live in
Kernel, and we’ve added new methods:tap(),equals(),hash()andenumFor(). - The double inclusion problem is now fixed; no current Ruby implementation seems to support this properly.
- Ancestor and method lookups are now cached so
callSuperruns about twice as fast. - Classes can be named to generate
displayNameon methods for use with the WebKit debugger.
Most code based on version 1.x will be compatible with this release, but there a few issues to be aware of. If you have code you cannot update to 2.x at present, 1.6 is still available:
Acknowledgements
JS.Class was initially inspired by, and borrows ideas from, these open-source projects:
- The Prototype framework, © 2005-2009 Sam Stephenson
- Alex Arnell’s Inheritance library, © 2006, Alex Arnell
- Base, © 2006-9, Dean Edwards
The standard library has been influenced by techniques demonstrated in Pro JavaScript Design Patterns, and contains ports of a few standard Ruby modules.
JS.Class is © 2007–2009 James Coglan. You can find update announcements via
my blog. The source code is hosted on
Github.