Ale*_*exH 53 javascript functional-programming
我正在尝试编写一个JavaScript函数,它将返回其第一个参数(函数),其所有其余参数作为该函数的预设参数.
所以:
function out(a, b) {
document.write(a + " " + b);
}
function setter(...) {...}
setter(out, "hello")("world");
setter(out, "hello", "world")();
会两次输出"你好世界".对于setter的一些实现
我在第一次尝试时遇到了操纵arguments数组的问题,但似乎有更好的方法来做到这一点.
Jas*_*ing 96
首先,你需要一个部分 - 部分和咖喱之间存在差异 - 如果没有框架,这就是你需要的全部内容:
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);
};
}
Run Code Online (Sandbox Code Playgroud)
现在,使用您的示例,您可以完全按照以下方式执行操作:
partial(out, "hello")("world");
partial(out, "hello", "world")();
// and here is my own extended example
var sayHelloTo = partial(out, "Hello");
sayHelloTo("World");
sayHelloTo("Alex");
Run Code Online (Sandbox Code Playgroud)
该partial()函数可用于实现,但不是 currying.以下是关于差异的博客文章的引用:
在部分应用程序接受函数的情况下,从中构建一个函数,该函数接受较少的参数,currying构建函数,这些函数通过函数组合获取多个参数,每个参数都采用一个参数.
希望有所帮助.