Skip to content

Instantly share code, notes, and snippets.

@couto
Created July 17, 2013 21:34
Show Gist options
  • Save couto/6024739 to your computer and use it in GitHub Desktop.
Save couto/6024739 to your computer and use it in GitHub Desktop.
/**
* klass
*
* @module klass
* @example
*
* var Animal = klass({
* initialize: function () {},
* dealloc: function () {}
* }),
*
* Carnivorous = Animal.extend({
* initialize: function () {
* this.parent();
* }
* }),
*
* Domestic = Animal.extend(Animal, {
* initialize: function () {
* this.parent()
* }
* }),
*
* Cat = klass.compose(Carnivorous, Domestic),
*
* HyperactiveCat = Cat.implement({
* run: function () {},
* jump: function () {}
* }),
*
* sina = HyperactiveCat.create()
*
*/
define([
//<validation>
'mout/lang/isObject',
'mout/lang/isArguments',
//</validation>
'mout/lang/isFunction',
'mout/lang/toArray',
'mout/object/mixIn',
'mout/lang/createObject'
], function (
//<validation>
isObject,
isArguments,
//</validation>
isFunction,
toArray,
mixIn,
createObject
) {
'use strict';
/**
* Base object or the first object in the inheritance chain
* @type {Object}
*/
var Klass = {
/**
* create
* create instances of the current object
*
* @public
* @param {Mixed} [mixed]* [description]
* @return {Object} newly created object
*/
create : function () {
// create a new object with Klass as its prototype
var child = createObject(this, {});
if (isFunction(child.__module)) {
// if the object contains a module
// we need to call it and fix the context
child.__module.call(child);
}
if (isFunction(child.initialize)) {
// initialize is the 'contructor' function of the given object
// if it's present it will be called at creation time and
// the parameters given to create will be passed through
child.initialize.apply(child, toArray(arguments));
}
// return the newly created child
return child;
},
/**
* extend
*
* @param {Object} [varname] [description]
* @return {Object}
*/
extend: function (methods) {
//<validation>
if (!isObject(methods)) {
throw new TypeError('Argument must be an Object');
}
//</validation>
return createObject(this, methods);
},
/**
* compose
*
* @param {Object} [several...]+ [description]
* @return {Object}
*/
compose: function () {
var args = toArray(arguments);
// mixIn the object itself with the newly given ones.
// affecting the current object.
return mixIn.apply(this, [this].concat(args));
},
/**
* module
*
* @param {Function} fn [description]
* @return {Object} [description]
*/
module: function (fn) {
var child = createObject(this, {});
child.__module = fn;
return child;
}
};
//<testing>
window.__PRIVATE = window.__PRIVATE || {};
window.__PRIVATE.klass = {
Klass: Klass
};
//</testing>
return function klass(methods) {
//<validation>
if (!isObject(methods)) {
throw TypeError('Argument must be an Object');
}
//</validation>
return createObject(Klass, methods);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment