Created
November 26, 2011 05:33
-
-
Save lifeicd/1395098 to your computer and use it in GitHub Desktop.
Class Lib
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
| var Class = function(parent){ | |
| var klass = function(){ | |
| this.init.apply(this, arguments); | |
| }; | |
| // Change klass' prototype | |
| if (parent) { | |
| var subclass = function() { }; | |
| subclass.prototype = parent.prototype; | |
| klass.prototype = new subclass; | |
| }; | |
| klass.prototype.init = function(){}; | |
| klass.fn = klass.prototype; | |
| // Adding a proxy function | |
| klass.proxy = function(func){ | |
| var self = this; | |
| return(function(){ | |
| return func.apply(self, arguments); | |
| }); | |
| } | |
| // extend: static method | |
| klass.extend = function(obj){ | |
| var extended = obj.extended; | |
| for(var i in obj){ | |
| klass[i] = obj[i]; | |
| } | |
| if (extended) extended(klass) | |
| } | |
| // include: instance method | |
| klass.include = function(obj){ | |
| // ... | |
| for(var i in obj){ | |
| klass.prototype[i] = obj[i] | |
| } | |
| ///... | |
| } | |
| // Add the function on instances too | |
| klass.fn.proxy = klass.proxy; | |
| return klass; | |
| }; | |
| // inheritance | |
| var Animal = new Class; | |
| Animal.include({ | |
| breath: function() { | |
| console.log('whew!'); | |
| } | |
| }); | |
| var Cat = new Animal; | |
| var tom = new Cat; | |
| tom instanceof Cat // true | |
| tom instanceof Animal // true | |
| tom.breath(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment