Skip to content

Instantly share code, notes, and snippets.

@jedireza
Forked from ryanflorence/interview.js
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedireza/a496edadb28c88c08299 to your computer and use it in GitHub Desktop.
Save jedireza/a496edadb28c88c08299 to your computer and use it in GitHub Desktop.
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