我正在尝试编写一个JavaScript函数,该函数将返回其第一个参数(函数),并将其所有其他参数作为该函数的预设参数。
所以:
函数out(a,b){ document.write(a +“” + b); } 函数setter(...){...} setter(out,“ hello”)(“ world”); setter(out,“ hello”,“ world”)();
将输出两次“ hello world”。对于二传手的一些实现
我在第一次尝试时就遇到了处理arguments数组的问题,但是似乎会有更好的方法来做到这一点。
首先,您需要一个部分- 部分和咖喱之间是有区别的 -这就是您所需要的,而没有框架:
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);
};
}
现在,使用您的示例,您可以完全按照自己的意愿进行操作:
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()
函数可用于实现,但不是临时的。这是一篇博客文章中的区别引述:
在部分应用程序采用一个函数并从中构建一个采用较少参数的函数的情况下,currying通过函数的组合构建采用多个参数的函数,每个函数均采用一个参数。
希望有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句