Skip to content

Instantly share code, notes, and snippets.

@kctang
Created February 4, 2015 00:37
Show Gist options
  • Save kctang/eb9b692bb37031b71af5 to your computer and use it in GitHub Desktop.
Save kctang/eb9b692bb37031b71af5 to your computer and use it in GitHub Desktop.
define([], function () {
'use strict';
var Class = function (classProp) {
var parentClass = classProp.extends;
var Clazz = function (attributes) {
// load default values from class attributes
attributes = defaults(attributes, classProp.attributes);
// --- call parent class's constructor
if (parentClass !== undefined) {
// load default values from parent class attributes
attributes = defaults(attributes, parentClass.defaultAttributes);
parentClass.call(this, attributes);
}
this.attributes = attributes;
// call class's init method
var init = classProp.init;
if(init!==undefined) {
init.call(this);
}
// bind "this" to "this.attributes"
// TODO: bind to this.attributes to change scope?
// TODO: is this a good idea?
for(var name in classProp.methods) {
this[name] = this[name].bind(this.attributes);
}
};
// --- use parent class's prototype
if (parentClass !== undefined) {
Clazz.prototype = Object.create(parentClass.prototype);
}
// --- declare prototype methods
for (var methodName in classProp.methods) {
Clazz.prototype[methodName] = classProp.methods[methodName];
}
// --- special stuff
Clazz.defaultAttributes = classProp.attributes;
Clazz.init = classProp.init;
// --- private functions
function defaults(attributes, defaultAttributes) {
attributes = attributes || {};
for (var names in defaultAttributes) {
if (attributes[names] === undefined) {
// attribute not specified during object creation, set the default
attributes[names] = defaultAttributes[names];
}
}
return attributes;
}
return Clazz;
};
return Class;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment