Skip to content

Instantly share code, notes, and snippets.

@kaichen
Created February 25, 2011 09:10
Show Gist options
  • Select an option

  • Save kaichen/843556 to your computer and use it in GitHub Desktop.

Select an option

Save kaichen/843556 to your computer and use it in GitHub Desktop.
// 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