Skip to content

Instantly share code, notes, and snippets.

@gunderwonder
Created September 21, 2011 17:06
Show Gist options
  • Save gunderwonder/1232674 to your computer and use it in GitHub Desktop.
Save gunderwonder/1232674 to your computer and use it in GitHub Desktop.
A simple JavaScript inheritance system
/*
* A simple JavaScript inheritance system
* (Like Prototype's `Class.create()`, only without the crazy method wrapping and function decompilation)
*
* Usage
* var A = Class.create({
* // `initialize` is the constructor
* initialize : function(x, y) {
* this.x = x;
* this.y = y;
* }
* toString : function() { return [x, y].join(' '); }
* });
*
* // `B` is a child of `A`
* var B = Class.create(A, {
* initialize : function(x, y, z) {
* // call this.<methodname>.$super to use the superclass implementation
* this.initialize.$super(x, y);
* this.z = z;
* },
* toString : function() { return [x, y, z].join(' '); }
* });
*
* var a = new A(10, 10), b = new B(10, 10, 20);
* a.toString() => '10 10'
* b.toString() => '10 10 20'
*/
var Class = (function() {
function create(baseclass, methods) {
if (typeof methods == 'undefined') {
methods = baseclass;
baseclass = null;
}
methods.initialize = methods.initialize || function() { };
var constructor = function() {
var that = this;
for (var k in methods) {
(function (k) {
methods[k].$super = function() {
constructor.superclass[k].apply(that, arguments);
}
})(k);
}
methods.initialize.apply(this, arguments);
}
if (baseclass) {
var subclass = function() { }
subclass.prototype = baseclass.prototype;
constructor.prototype = new subclass;
constructor.superclass = baseclass.prototype;
}
constructor.prototype.constructor = constructor;
for (var k in methods)
constructor.prototype[k] = methods[k]
return constructor;
}
return { create : create };
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment