Created
September 28, 2010 18:47
-
-
Save jboesch/601538 to your computer and use it in GitHub Desktop.
attachClass init and self
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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