Created
May 10, 2011 23:57
-
-
Save sciolist/965646 to your computer and use it in GitHub Desktop.
Minimal JavaScript inheritance
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
| function Class() { } | |
| Class.extend = function(data) { | |
| var cls = data.init || function(){}; | |
| cls.base = data.__proto__ = this.prototype; | |
| cls.extend = arguments.callee; | |
| cls.prototype = data; | |
| return cls; | |
| }; |
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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Testing...</title> | |
| </head> | |
| <body> | |
| <h5>(this writes to console.log, so check that out..)</h5> | |
| <!-- onclick = lazy --> | |
| <br /><button onclick="testCreatePirate()">Create pirate!</button> | |
| <br /><button onclick="testCreateCaptain()">Create captain!</button> | |
| <script type="text/javascript" src="class.js"></script> | |
| <script type="text/javascript"> | |
| var Person = Class.extend({ | |
| init: function() { | |
| console.log("New person"); | |
| }, | |
| greet: function(tgt) { | |
| console.log("Hey", tgt); | |
| } | |
| }); | |
| var Pirate = Person.extend({ | |
| greet: function(tgt) { | |
| console.log("Yarr", tgt); | |
| } | |
| }); | |
| var Captain = Pirate.extend({ | |
| init: function() { | |
| console.log("New captain"); | |
| Captain.base.init.call(this); | |
| }, | |
| speak: function() { | |
| console.log("Avast, ye bilge rats!"); | |
| } | |
| }); | |
| </script> | |
| <script type="text/javascript"> | |
| function testCreatePirate() { | |
| console.log("-- test create pirate"); | |
| var pirate = new Pirate(); | |
| pirate.greet("Shelly"); | |
| } | |
| function testCreateCaptain() { | |
| console.log("-- test create pirate captain"); | |
| var pirate = new Captain(); | |
| console.log(pirate instanceof Pirate); | |
| pirate.greet("Shelly"); | |
| pirate.speak(); | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment