我正在阅读Javascript中的 函数currying 。我得到了概念,示例很容易理解。
然而,该文章的作者说,对于多个嵌套的 return 来说,过多地调整函数可能会很乱,并且显示了一个函数来 curry 另一个函数作为参数传递。
var curryIt = function(uncurried) {
var parameters = Array.prototype.slice.call(arguments, 1);
return function() {
return uncurried.apply(this, parameters.concat(
Array.prototype.slice.call(arguments, 0)
));
};
};
然后以这种方式应用
var greeter = function(greeting, separator, emphasis, name) {
console.log(greeting + separator + name + emphasis);
};
var greetHello = curryIt(greeter, "Hello", ", ", ".");
greetHello("Heidi"); //"Hello, Heidi."
greetHello("Eddie"); //"Hello, Eddie."
curryIt 是 curry 其他功能的功能。这到底是怎么回事?
虽然我没有陌生的代码,但我似乎没有得到它。
答案 0 :(得分:1)
从技术上讲,这是部分应用,但这两个想法是very closely related.
无论如何,让我们分解你的代码:
var curryIt = function(uncurried) {
// Get all of the parameters except for `uncurried`
var parameters = Array.prototype.slice.call(arguments, 1);
// Return a new function such that...
return function() {
// The function you passed in, `uncurried` is called
return uncurried
// apply - Use an array for arguments instead of positional arguments
// i.e, f(a, b, c) === f.apply(this, [a, b, c])
.apply(
// Set the value of `this` in `uncurried`
this,
// Create a copy of the original `parameters` array and add...
parameters.concat(
// ...the arguments that were passed to the anonymous function
Array.prototype.slice.call(arguments, 0)
));
};
};
通过查看parameters
如何变化,您可以了解其工作原理。
var curryIt = function(uncurried) {
var parameters = Array.prototype.slice.call(arguments, 1);
console.log('curryIt: ' + parameters.join(' '));
return function() {
var newParams = Array.prototype.slice.call(arguments, 0);
console.log('anonymous: ' + newParams.join(' '));
// Prepare the arguments here so we can see them
var args = parameters.concat(newParams);
console.log('Full call: ' + args.join(' '));
return uncurried.apply(this, args);
};
};
function f(a, b, c, d) {
console.log('Finished: ' + [a, b, c, d].join(' '));
console.log(' ');
}
var g = curryIt(f, 1, 2);
g(3, 4);
g(10, 20);