Skip to content

Instantly share code, notes, and snippets.

@gosukiwi
Created June 18, 2014 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosukiwi/c571930efbeb1ef1190f to your computer and use it in GitHub Desktop.
Save gosukiwi/c571930efbeb1ef1190f to your computer and use it in GitHub Desktop.
/**
* Object Oriented JS Utils
*/
var oo = {
/**
* `methods` parameter is optional, if base is not
* defined assume it was defined in method's place,
* that way this method can be called as follows:
*
* `var Class = oo.extend(function () {}, BaseClass);`
*
* Or if you need to also specify shared methods
*
* `var Class = oo.extend(function () {}, {
* 'myMethod': function () {} }, BaseClass);`
*/
extend: function (constructor, methods, base) {
if(base === undefined) {
base = methods;
methods = undefined;
}
// A generic constructor function we'll return from this method
function o() {
var self = this,
baseRan = false;
//base.apply(this, args);
self._base = function () {
base.apply(self,
Array.prototype.slice.call(arguments, 0));
baseRan = true;
};
constructor.apply(self,
Array.prototype.slice.call(arguments, 0));
if(!baseRan) {
throw 'Forgot to call _base()?';
}
}
o.prototype = Object.create ? Object.create(base.prototype) : new base();
o.prototype.constructor = o;
// _super is a "private" variable all instances have, and
// whenever an attribute from the child object overrides an
// attribute from the base object, the base method is stored
// in _super, so you can access it inside your object as
// `this._super.myBaseMethod`.
o.prototype._super = {};
// If the methods arguments is defined it must be an object
// literal with all the methods for this "class", store them
// in the `prototype` so they are stored in a single place in
// memory, meaning all instances will share the methods
if(methods !== undefined && typeof methods === 'object') {
for(var attr in methods) {
if(o.prototype[attr]) {
o.prototype._super[attr] = o.prototype[attr];
}
o.prototype[attr] = methods[attr];
}
}
// Finally return the generated constructor function
return o;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment