我正在尝试编写一个 JavaScript 函数,它将返回它的第一个参数(函数)及其所有其余参数作为该函数的预设参数。
所以:
function out(a, b) { document.write(a + " " + b); } function setter(...) {...} setter(out, "hello")("world"); setter(out, "hello", "world")();
会输出两次“hello world”。对于setter的一些实现
我在第一次尝试操作参数数组时遇到了问题,但似乎有更好的方法来做到这一点。
最佳答案
首先,您需要一个部分 - there is a difference between a partial and a curry - 这就是您所需要的,没有框架:
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)。这是来自 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.
希望对您有所帮助。
关于javascript - 如何在 JavaScript 函数调用中预先设置参数? (部分功能应用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/321113/