gpt4 book ai didi

javascript - 调用柯里化(Currying)函数而不传递另一个参数

转载 作者:行者123 更新时间:2023-12-03 06:00:45 26 4
gpt4 key购买 nike

我有一个简单的函数,需要一个参数

fn = function(argument) {console.log(argument)}

setInterval中,我想调用该函数并传递一个外部变量:

argument = 1
setInterval(<MY FUNCTION WITH ACCESS TO ARGUMENT>, 1000)

我意识到我可以使用高阶函数来做到这一点,即

fn = function(argument) {
function () {
console.log(argument)
}
}
argument = 1
setInterval(fn(argument), 1000)

这确实有效,但我想知道是否可以用 curry 来完成。

我已经尝试过:

fn = _.curry(fn)("foo")
// since the function takes only one argument,
// here it is invoked and no longer can be
// passed as a function to setInterval

fn = _.curry(fn, 2)("foo")
// setting the arity to 2 makes it so the function
// isn't invoked. But setInterval does not pass
// the additional argument and so it never ends
// up getting invoked.

我觉得这些 curry 示例中缺少一些东西。我或者 curry 在这里没有帮助吗?

最佳答案

确实 lodash _.curry 似乎不适合您的用例。

但是您可以使用普通 JavaScript bind为此:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Syntax

fun.bind(thisArg[, arg1[, arg2[, ...]]])

在您的情况下,您的代码将如下所示:

fn = function(argument) {console.log(argument)}

var argument = 1
setInterval(fn.bind(this, argument), 1000)

Lodash 替代品

如果您确实想以 lodash 方式执行此操作,则 fn.bind(thisArg, ...args) 的等价物是 _.bind(fn, thisArg, ...参数)。如果您对设置 this 引用不感兴趣,那么您可以使用 _.partial(fn, ...args) 保存一个参数。 :

Creates a function that invokes func with partials prepended to the arguments it receives. This method is like _.bind except it does not alter the this binding.

关于javascript - 调用柯里化(Currying)函数而不传递另一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757281/

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