Skip to content

Instantly share code, notes, and snippets.

@Ptico
Created April 15, 2012 01:20
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 Ptico/2389157 to your computer and use it in GitHub Desktop.
Save Ptico/2389157 to your computer and use it in GitHub Desktop.
Just an experiment with JS object model and ES5 functions
var Hello = Class({
attrReader: "val",
initialize: function(val) {
this.val = val;
},
publicFn: function() {
console.log(this.val);
this.privateFn();
},
private: {
privateFn: function() {
console.log("private");
}
}
});
var test = Hello.new(3);
var Class = (function() {
function klass(definition) {
var Class,
self = {},
mixins = [],
readers = [],
accessors = [],
defs;
if (definition.initialize) {
var ctor = definition.initialize;
Class = function() {
ctor.apply(self, arguments);
};
} else Class = new Function();
Object.defineProperty(Class, "definition", {
value: definition
});
if (definition.extends) {
var ext = definition.extends.definition;
delete definition.extends;
defs = [ext, definition];
} else defs = [definition];
for (var i = 0, l = defs.length; i < l; i++) {
var def = defs[i];
for (var key in def) {
var val = def[key];
if (key == "initialize") {
if (l > 1 && i === 0) self.super = val.bind(self);
}
else if (key == "include") { mixins = typeof val == "string" ? [val] : val } // FIXME - merge instead of set
else if (key == "attrReader") { readers = typeof val == "string" ? [val] : val } // FIXME - merge instead of set
else if (key == "attrAccessor") { accessors = typeof val == "string" ? [val] : val } // FIXME - merge instead of set
else {
if (key == "private" || key == "protected") {
for (var pkey in val) {
if (val.hasOwnProperty(pkey)) {
var pval = val[pkey];
self[pkey] = (typeof pval == "function") ? pval.bind(self) : pval;
}
}
} else {
var bound = (typeof val == "function") ? val.bind(self) : val;
self[key] = bound;
Class.prototype[key] = bound;
}
}
} // for
}
for (var i = 0; i < readers.length; i++) {
var prop = readers[i];
Object.defineProperty(Class.prototype, prop, {
get: function() {
return self[prop];
}
});
}
for (var i = 0; i < accessors.length; i++) {
var prop = accessors[i];
Object.defineProperty(Class.prototype, prop, {
get: function() {
return self[prop];
},
set: function(val) {
self[prop] = val;
}
});
}
Class.new = function() {
var args = Array.prototype.slice.call(arguments),
bound;
args.unshift(self);
var bound = Function.prototype.bind.apply(Class, args);
return new bound();
};
return Class;
};
return klass;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment