Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Created November 27, 2012 15:08
Show Gist options
  • Save jfromaniello/4154706 to your computer and use it in GitHub Desktop.
Save jfromaniello/4154706 to your computer and use it in GitHub Desktop.
another twist in javascript partial application. Bind
var salutator = {
name: 'jose',
greet: function(greeting, person) {
console.log(greeting + ' ' + person + '. ' + this.name + ' salutates you.');
}
};
salutator.greet('hello', 'Mark');
//hello mark, jose salutates you.
var goodByer = salutator._partial('greet', 'good bye');
goodByer('Remigio');
//good bye Remigio, jose salutates you.
/*
* Adds a non enumerable _partial function to the object prototype
* that when called returns the partial application of the given
* function (first parameter) with n resolved parameters.
*/
Object.defineProperty(Object.prototype, '_partial', {
set: function(){},
get: function(){
var methodOwner = this;
return function (){
var methodName = arguments[0],
args = [];
for (var i = 1; i < arguments.length; i++){
args.push(arguments[i]);
}
return function(){
var allArgs = args.slice(0);
for (var i = 0; i < arguments.length; i++){
allArgs.push(arguments[i]);
}
return methodOwner[methodName].apply(methodOwner, allArgs);
};
};
},
configurable: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment