Skip to content

Instantly share code, notes, and snippets.

@rapha
Created August 10, 2009 09:52
Show Gist options
  • Save rapha/165115 to your computer and use it in GitHub Desktop.
Save rapha/165115 to your computer and use it in GitHub Desktop.
Javascript mixin implementation
function mixable() {
var parents = [];
return {
mixin: function(parent) { parents.push(parent); },
__noSuchMethod__: function(id, args) {
for each (var parent in parents) {
if (typeof parent[id] === 'function') {
return parent[id].apply(this, args);
}
}
}
};
}
var obj = mixable();
obj.mixin({
combine: function(a, b){ return a + b; },
});
obj.mixin({
combine: function(a, b){return a * b}, // order of mixing-in determines precedence, so this will never be called
subtract: function(a, b) { return a - b }
});
print(obj.combine(1,2));
print(obj.subtract(7,6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment