Following on an older post of mine, I decided to write a new article about an(other) implementation of OOP Classes in JavaScript. This is something that brings a lot of value from very few lines of code and I want to share it with everyone and see how it can be improved.
First let’s see the code (you should check here for the latest version) and then I’ll try and explain the relevant benefits/features but jump straight to the goodies if you like, knock yourself out! 🙂
/**
* Class.js: A class factory.
*/
function Class(members) {
// setup proxy
var Proxy = function() {};
Proxy.prototype = (members.base || Class).prototype;
// setup constructor
members.init = members.init || function() {
if (Proxy.prototype.hasOwnProperty("init")) {
Proxy.prototype.init.apply(this, arguments);
}
};
var Shell = members.init;
// setup inheritance
Shell.prototype = new Proxy();
Shell.prototype.base = Proxy.prototype;
// setup identity
Shell.prototype.constructor = Shell;
// setup augmentation
Shell.grow = function(items) {
for (var item in items) {
if (!Shell.prototype.hasOwnProperty(item)) {
Shell.prototype[item] = items[item];
}
}
return Shell;
};
// attach members and return the new class
return Shell.grow(members);
}
Observations
Each Class points to (via .prototype) a corresponding Proxy object that holds the class’s member fields. In turn, this Proxy points to (via .prototype) the Proxy of the inherited class (i.e. the super-Class) and so on. So, each Class points to its own Proxy which points to the ancestor Proxy and so on, until the top level ancestor is reached. (more…)