Skip to content

Instantly share code, notes, and snippets.

@steida
Created May 19, 2009 21:08
Show Gist options
  • Save steida/114404 to your computer and use it in GitHub Desktop.
Save steida/114404 to your computer and use it in GitHub Desktop.
/*
*
* Class - JavaScript prototype inheritance sugar
*
* - reference to parent class is stored in static property superclass
* - in every method, you can call parent method .parent(..)
* - todo: methods with underscore prefix are protected
*
*/
QWE(function() {
// param - function, object or nothing
Class = new Type('Class', function(param) {
var object = Type.isFunction(param) ? { initialize: param} : param || {};
var constructor = function() {
if (this.initialize) this.initialize.apply(this, arguments);
} .extend(this);
for (var key in Class.Initializers) Class.Initializers[key].call(constructor, object);
return constructor;
});
/*
* Mutators are used for class creation, they are fired in the order.
*/
Class.Initializers = {
Extends: function(object) {
this.superclass = object.Extends || Class;
this.prototype = Function.beget(this.superclass);
this.mixin(object);
},
Mixins: function(object) {
if (object.Mixins) Array.from(object.Mixins).forEach(this.mixin, this);
this.prototype.constructor = this;
}
};
var wrap = function(name, fn, parent) {
var proto = parent.prototype;
return function() {
this.parent = proto[name];
var result = fn.apply(this, arguments);
this.parent = parent;
return result;
}
};
Class.mixin({
// param - class or object
mixin: function(param) {
var object = Type.isClass(param) ? param.prototype : param;
Object.forEach(object, function(value, key) {
this.prototype[key] = Type.isFunction(value) ? wrap(key, value, this.superclass) : value;
}, this);
return this;
} .setOne()
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment