Created
February 25, 2011 09:10
-
-
Save kaichen/843556 to your computer and use it in GitHub Desktop.
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
| // try ruby-like mixin in javascript | |
| function mixin(object, name, fn) { | |
| var orignal = object[name]; | |
| object[name] = function() { | |
| try { | |
| this.super = orignal; | |
| return fn.apply(this, arguments); | |
| } finally { | |
| delete this.super; | |
| } | |
| }; | |
| } | |
| function Hacker() {} | |
| Hacker.prototype.hello = function () { | |
| console.log("hello"); | |
| }; | |
| var other_hello = function () { | |
| console.log("in other_hello {"); | |
| this.super(); | |
| console.log("} in other_hello"); | |
| } | |
| var another_hello = function () { | |
| console.log("in another_hello {"); | |
| this.super(); | |
| console.log("} in another_hello"); | |
| } | |
| var kai = new Hacker(); | |
| mixin(kai, "hello", other_hello); | |
| mixin(kai, "hello", another_hello); | |
| kai.hello(); | |
| // RESULT: | |
| // in another_hello { | |
| // in other_hello { | |
| // hello | |
| // } in other_hello | |
| // } in another_hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment