Created
December 9, 2012 04:21
-
-
Save shinypb/4243322 to your computer and use it in GitHub Desktop.
A relatively small, pretty crappy inheritance/class thingy
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
| // Here's the defineClass function | |
| (function() { | |
| function defineClass() { | |
| var kDefineClassMagicValue = 'defineClass_do_not_call_user_provided_constructor'; | |
| var args = Array.prototype.slice.apply(arguments); | |
| var className, superClassName, constructor, properties; | |
| className = args.shift(); | |
| if (typeof args[0] == 'string') { | |
| superClassName = args.shift(); | |
| } | |
| if (typeof args[0] == 'function') { | |
| constructor = args.shift(); | |
| } else if(superClassName) { | |
| constructor = window[superClassName].prototype.constructor; | |
| } else { | |
| constructor = function() {}; | |
| } | |
| if (typeof args[0] == 'object') { | |
| properties = args.shift(); | |
| } else { | |
| properties = {}; | |
| } | |
| (function(className, superClassName, constructor, properties) { | |
| function theNewClass() { | |
| this.className = className; | |
| this.constructor = constructor; | |
| if (arguments[0] != kDefineClassMagicValue) { | |
| this.constructor.apply(this, arguments); | |
| } | |
| } | |
| if (superClassName) { | |
| theNewClass.prototype = new window[superClassName](kDefineClassMagicValue); | |
| } | |
| theNewClass.constructor = constructor; | |
| theNewClass.className = className; | |
| Object.keys(properties).forEach(function(key) { | |
| theNewClass.prototype[key] = properties[key]; | |
| }.bind(this)); | |
| window[className] = theNewClass; | |
| })(className, superClassName, constructor, properties); | |
| } | |
| window.defineClass = defineClass; | |
| })(); | |
| // This is a class declaration | |
| defineClass('SMAgent', function(engine) { | |
| this.engine = engine; | |
| }, { | |
| tick: function() { | |
| console.log('agent tick'); | |
| } | |
| }); | |
| // and here's a subclass | |
| defineClass('SMPlayer', 'SMAgent', { | |
| isPlayer: true, | |
| tick: function() { | |
| console.log('player tick'); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment