在不传递另一个参数的情况下调用柯里化函数
invoking curried function without passing another argument
我有一个接受一个参数的简单函数
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.
我觉得这些咖喱示例中缺少一些东西。我是,还是咖喱对这里没有帮助?
确实 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, ...args)
。如果您对设置 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.
我有一个接受一个参数的简单函数
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.
我觉得这些咖喱示例中缺少一些东西。我是,还是咖喱对这里没有帮助?
确实 lodash _.curry
似乎不适合您的用例。
但是你可以使用原版 JavaScript bind
:
The
bind()
method creates a new function that, when called, has itsthis
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, ...args)
。如果您对设置 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 thethis
binding.