javascript - 如何在 JavaScript 函数调用中预先设置参数? (部分功能应用)

标签 javascript functional-programming

我正在尝试编写一个 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/

相关文章:

javascript - 隐藏嵌入式框架场景

javascript - AngularJs POST 方法到 springboot api

java - 如何使用 lambda 在 Java 中实现两个抽象方法?

java - RxJava 收集() & takeUntil()

javascript - forEach 运算符在没有订阅的情况下被评估

javascript - 在 jQuery 中制作 DOM 的副本

javascript - 从文本文件获取canvasjs的数据点

javascript - 如何停止页面重定向

javascript - 通过 ramda.js 使用高阶函数进行映射

swift - 如何快速将两个 [String] 映射为一个 [Record]?