Created
August 10, 2009 09:52
-
-
Save rapha/165115 to your computer and use it in GitHub Desktop.
Javascript mixin implementation
This file contains 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 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