gpt4 book ai didi

javascript - 接受一个值并返回一个返回该值的函数的函数叫什么?

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

我正在使用 Lodash 和 Compose 尝试一种更实用的 Javascript 风格。我注意到有时我需要一个返回值的函数。所以想知道这叫什么,这样我就可以查明 Lodash 是否真的有这个方法。

var returnFn = function (i) {
return function () {
return i;
};
};

例子:

_.compose(doSomething, returnFn({ foo: 'bar' });

代替:

_.compose(doSomething, function () {
return { foo: 'bar' };
});

最佳答案

What do you call a function that takes a value and returns a function that returns that value?

你所拥有的似乎是一个 curryied identity function ,在 Haskell 中称为 const .当它返回一个函数时,它是一个 higher order function ,也许也称为函数 factory .返回的函数 - constant function - 是 closure因为它可以访问外部函数的参数。

so I can find out if Lodash actually has this method.

不,它没有。但是,您可以通过 _.binding 轻松地自己编写它。 _.partial_.identity功能:

var returnFn = _.bind(_.partial, null, _.identity);

虽然你的简单实现会快很多......

_.compose(doSomething, returnFn({ foo: 'bar' }));

你在那里做的只是partial application , 你不应该为它使用 compose 。一起去

_.partial(doSomething, {foo: 'bar'});

关于javascript - 接受一个值并返回一个返回该值的函数的函数叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18659764/

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