-
-
Save jedireza/a496edadb28c88c08299 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
function delegate (child) { | |
// make it happen | |
return function inner () { | |
var self = this; | |
var func = Object.getOwnPropertyNames(this).filter(function (prop) { | |
return inner === self[prop]; | |
}).pop(); | |
return this[child][func].apply(this[child], arguments); | |
}; | |
} | |
// usage | |
var obj = { | |
math: { | |
x: 2, | |
add: function (y) { | |
return this.x + y; | |
}, | |
multiply: function (y) { | |
return this.x * y; | |
} | |
}, | |
add: delegate('math'), | |
multiply: delegate('math') | |
}; | |
// test cases | |
console.assert( obj.add(1) === 3 ); | |
console.assert( obj.multiply(3) === 6 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment