Skip to content

Instantly share code, notes, and snippets.

@jamesflorentino
Created November 18, 2012 01:47
Show Gist options
  • Save jamesflorentino/4102711 to your computer and use it in GitHub Desktop.
Save jamesflorentino/4102711 to your computer and use it in GitHub Desktop.
Useable in both CommonJS and AMD
/**
* AMD/CommonJS Class Module
* Copyright (c) 2012 James Florentino
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* Derived from John Resig's Simple Prototypal Inheritance http://ejohn.org/
* UMD compatible
**/
(function() {
"use strict"; // Comply to ES3 standards
function factory(require, exports, module) {
/**
* Flag to prevent the Class.proto.init from being invoked during initialization
* @type {Boolean}
*/
var start = true;
/**
* Creates a shim for invoking a this.parent() command
* @param {object} prototype
* @param {string} name
* @param {function} method
* @return {Function}
*/
function protoParent(prototype, name, method) {
return function() {
this.parent = prototype[name];
return method.apply(this, arguments);
};
}
/**
* Extends an object's properties and assign them as prototypes in a Function
* @param BaseClass
* @param properties
* @return {Function}
*/
function extend(BaseClass, properties) {
var parent = BaseClass.prototype;
start = false;
var prototype = new BaseClass();
start = true;
var attribute;
// iterate over the properties
for(var name in properties) {
if (properties.hasOwnProperty(name)) {
attribute = properties[name];
prototype[name] = typeof parent[name] === 'function' && typeof properties[name] === 'function' ?
protoParent(parent, name, attribute) :
attribute;
}
}
// Create a fresh sub-class
function Class() {
if (start && this.init.apply) {
this.init.apply(this, arguments);
}
}
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = function(attr) {
return extend(Class, attr);
};
return Class;
}
return module.exports = extend(function(){}, {});
}
// Defines a module that works in CommonJS and AMD.
if (typeof define === 'function') {
define(factory);
} else if (typeof exports === 'object' && typeof module === 'object') {
factory(require, exports, module);
}
})();
// usage
var Human = Class.extend({
init: function() {
this.health = 10;
}
});
var Orc = Human.extend({
init: function() {
this.parent();
this.health *= 3;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment