问题描述
我正在尝试编写一个 JavaScript 函数,该函数将返回其第一个参数(函数)及其所有其余参数作为该函数的预设参数.
I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function.
所以:
function out(a, b) {
document.write(a + " " + b);
}
function setter(...) {...}
setter(out, "hello")("world");
setter(out, "hello", "world")();
会输出两次hello world".一些 setter 的实现
Would output "hello world" twice. for some implementation of setter
我在第一次尝试时遇到了操作参数数组的问题,但似乎有更好的方法来做到这一点.
I ran into an issue with manipulating the arguments array on my first try, but it seems there would be a better way to do this.
推荐答案
首先,你需要一个局部的 - partial 和 curry 之间有区别 - 这就是你所需要的,没有框架:
First of all, you need a partial - there is a difference between a partial and a curry - and here is all you need, without a framework:
function partial(func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}
现在,使用您的示例,您可以完全按照您的要求进行操作:
Now, using your example, you can do exactly what you are after:
partial(out, "hello")("world");
partial(out, "hello", "world")();
// and here is my own extended example
var sayHelloTo = partial(out, "Hello");
sayHelloTo("World");
sayHelloTo("Alex");
partial()
函数可以用来实现,但不是柯里化.这是一篇关于差异的博文的引述:
The partial()
function could be used to implement, but is not currying. Here is a quote from a blog post on the difference:
当部分应用接受一个函数并从中构建一个接受较少参数的函数时,柯里化通过组合每个接受一个参数的函数来构建接受多个参数的函数.
希望有所帮助.
这篇关于如何在 JavaScript 函数调用中预设参数?(部分功能应用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!