Created
November 27, 2012 15:08
-
-
Save jfromaniello/4154706 to your computer and use it in GitHub Desktop.
another twist in javascript partial application. Bind
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
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. |
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
/* | |
* 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