Created
June 18, 2011 00:14
-
-
Save juandopazo/1032636 to your computer and use it in GitHub Desktop.
Simple inheritance implementation in JavaScript
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
| window.Class = (function () { | |
| function subclass(superclass, proto) { | |
| proto = proto || {}; | |
| var constructor = proto.constructor; | |
| if (!constructor) { | |
| constructor = proto.constructor = function () {}; | |
| } | |
| if (superclass) { | |
| var F = function () {}; | |
| F.prototype = superclass.prototype; | |
| constructor.prototype = new F(); | |
| constructor.superclass = superclass.prototype; | |
| } | |
| for (var p in proto) { | |
| if (proto.hasOwnProperty(p)) { | |
| constructor.prototype[p] = proto[p]; | |
| } | |
| } | |
| constructor.subclass = function (proto) { | |
| return subclass(constructor, proto); | |
| }; | |
| return constructor; | |
| } | |
| return function Class(proto) { | |
| return subclass(null, proto); | |
| }; | |
| }()); |
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 Person = Class({ | |
| constructor: function (name) { | |
| this.name = name; | |
| }, | |
| say: function (message) { | |
| return this.name + ' says: ' + message; | |
| } | |
| }); | |
| var Pirate = Person.subclass({ | |
| constructor: function (name) { | |
| Pirate.superclass.constructor('Capt\'n ' + name); | |
| }, | |
| say: function (message) { | |
| return Pirate.superclass.say(message) + ' Arr!!'; | |
| } | |
| }); | |
| var blackbeard = new Pirate('Blackbeard'); | |
| blackbeard.say('Ahoy, me mateys!'); // Capt'n Blackbeard says: Ahoy, me mateys! Arr!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment