Skip to content

Instantly share code, notes, and snippets.

@jboesch
Created September 28, 2010 18:47
Show Gist options
  • Select an option

  • Save jboesch/601538 to your computer and use it in GitHub Desktop.

Select an option

Save jboesch/601538 to your computer and use it in GitHub Desktop.
attachClass init and self
Object.prototype.attachClass = function(name, o){
this[name] = function(){
if(typeof(this.__init) == 'function'){
this.__init.apply(this, arguments);
}
};
var new_methods = {};
for(var m in o){
if(typeof(o[m]) == 'function'){
eval('new_methods[m] = ' + o[m].toString().replace(') {', '){ var self = this;'));
}
else {
new_methods[m] = o[m];
}
}
this[name].prototype = new_methods;
}
var Global = {};
Global.attachClass('Person', {
bodyType: 'alien',
__init: function(opts){
self.age = opts.age;
},
getAge: function(){
// OMG, ALIENS ARE 10 TIMES OLDER THAN US!
function verifyAge(age){
if(self.bodyType == 'alien'){
return Number(age) * 10;
}
return age;
}
return verifyAge(self.age);
}
});
var p = new Global.Person({ age: 34 });
console.log(p.getAge());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment