gpt4 book ai didi

javascript - 带有绑定(bind)的部分函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:54:02 26 4
gpt4 key购买 nike

所以最近我发现您可以使用 bind 对 js 执行部分函数/柯里化(Currying)。例如:

const foo = (a, b, c) => (a + (b / c))
foo.bind(null, 1, 2) //gives me (c) => (1 + (2 / c))

然而,这仅在您要 curry 的部分有序时才有效。如果我想使用绑定(bind)实现以下目标怎么办?

(b) => (1 + (b / 2))

尝试了各种解决方案,例如:

foo.bind(null, 1, null, 2)

有什么想法吗?是否可以使用 vanilla es6 来完成此操作?

最佳答案

您可以使用包装器对参数进行重新排序。

const
foo = (a, b, c) => a + b / c,
acb = (a, c, b) => foo(a, b, c);

console.log(acb.bind(null, 1, 2)(5));

关于javascript - 带有绑定(bind)的部分函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com