我如何在JavaScript函数调用中预先设置参数? (部分功能应用) [英] How can I pre-set arguments in JavaScript function call? (Partial Function Application)
问题描述
我试图编写一个JavaScript函数,它将返回其第一个参数(函数)及其所有参数的其余参数作为该函数的预设参数。
:function out(a,b){
document.write(a ++ b);
函数setter(...){...}
setter(out,hello)(world);
setter(out,hello,world)();
输出hello world两次。对于setter的一些实现
我在第一次尝试操作参数数组时遇到了一个问题,但似乎有更好的方法来完成此操作。 p>
首先,您需要一个部分 - 部分和咖喱之间存在差异 - 这里就是你所需要的,
$ b
函数partial(func / *,0..n args * /){
var args = Array.prototype.slice.call(arguments,1);
返回函数(){
var allArguments = args.concat(Array.prototype.slice.call(arguments));
返回func.apply(this,allArguments);
};
}
现在,使用您的示例,您可以完成以下任务:
partial(out,hello)(world);
partial(out,hello,world)();
//这里是我自己的扩展示例
var sayHelloTo = partial(out,Hello);
sayHelloTo(World);
sayHelloTo(Alex);
可以使用 partial()
函数来实现,但不是 currying。以下是来自 关于差异的博客文章 的引用:
如果部分应用程序接受一个函数并从中构建一个函数,该函数只需要较少的参数,而curry函数则通过函数的组合构建多个参数其中每一个都有一个参数。
希望有帮助。
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.
So:
function out(a, b) { document.write(a + " " + b); } function setter(...) {...} setter(out, "hello")("world"); setter(out, "hello", "world")();
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.
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");
The partial()
function could be used to implement, but is not currying. Here is a quote from a blog post on the difference:
Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.
Hope that helps.
这篇关于我如何在JavaScript函数调用中预先设置参数? (部分功能应用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!