Overview
classes.js
provides a more traditional object oriented programming pattern
than JavaScript's native prototype chaining.
In many cases, this is overkill and a more procedural or functional approach is
actually more appropriate in JavaScript. However, in some cases it is really
useful to have traditional OO features.
Features
- Multiple inheritance
- Namespaces
- Static (class-level) methods vs. instance methods
- Public, protected, and private levels of access
- Works in browser, or in node
- Only 5.5K (~1.8K minified)
Requires
Only dependency is atom.js, which is itself small and is included as a
submodule.
Unit Tests
To run from command line using node.js:
npm install atom-js
node test.js // brief
node test.js -v // verbose
To run in a browser, open test.html
.
Basic Example
When defining a class, attach static methods to thisClass
, and instance
methods to thisInstance
. Methods are protected by default, meaning they are
available to subclasses.
classes.define('myclass', ['base'], function (thisClass, protoClass) {
thisClass.staticMethod = function () {
return 'My Class is aw3s0m3!!1!';
};
thisClass.instance = function (thisInstance, protoInstance, expose) {
var foo = 'bar';
function privateMethod() {
return foo + ' baz';
}
thisInstance.protectedMethod = function () {
return thisClass.staticMethod() + ' ' + privateMethod();
};
thisInstance.publicMethod = function () {
return 'Here you go: ' + thisInstance.protectedMethod();
};
expose('publicMethod');
};
});
Once a class is defined, invoke it like this:
var instance = classes.instantiate('myclass');
console.log(instance.publicMethod());
Output:
"Here you go: My Class is aw3s0m3!!1! bar baz"
It is also possible to wait for a class to be defined:
classes.once('myclass', function () {
var instance = classes.instantiate('myclass');
});
Namespaces
By default, classes are defined in a global namespace. However, you can easily
create a new namespace if you want to ensure against class name collisions:
var myClassNamespace = classes.namespace();
myClassNamespace.define('myclass', [], function (thisClass) {
});
Multiple Inheritance
Multiple inheritance works by specifying an array of "superclasses" as the
second argument to .define()
, like so:
classes.define(
'myclass2',
['superclass1', 'superclass2'],
function (thisClass, protoClass) {
}
);
Inheriting Properties (Don't use primitives!)
It is possible to attach properties (as opposed to functions) to a class or
instance. However, primitive properties (simple string, number or boolean
values) are not recommended, because they will not stay in sync between class
and superclass. Instead, use accessor functions, or set properties as on object
or array that may have mutable members.