我正在阅读有关 JavaScript 中函数柯里化(Currying)的内容。我明白了这个概念,并且示例很容易理解。
但是,文章的作者说,对于多个嵌套的 return 来说,过多地柯里化(Currying)一个函数可能会很困惑,并展示了一个函数来柯里化(Currying)另一个函数函数作为参数传递。
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 是柯里化(Currying)另一个函数的函数。具体是怎样做的呢?
虽然没有我不熟悉的代码,但我似乎不明白。
最佳答案
从技术上讲,这是部分应用,但这两个想法是 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)
));
};
};
通过查看参数
如何变化,您可以了解它是如何工作的。
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);
关于javascript - 这个函数实际上是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985561/