问题描述
代替:
const fn = (ctx,a,...rest) => {};
const fnCurried = (ctx) => (b) => (...rest) => fn(ctx,b,...rest);
someFn("something",fnCurried(ctx));
我希望能够在顶层调用“fn”,所以我认为将上下文存储在另一种方法中会有所帮助,我不知道如何去做
const fnCurried = createCtx(ctx)
someFn("something",fnCurried(fn))
解决方法
在您的第一个示例中,someFn
将第二个参数作为以下形式的函数:
(b) => (...rest) => fn(ctx,b,...rest);
在您的第二个示例中,您希望保留此行为,这意味着调用 fnCurried(fn)
必须返回上述函数。我们可以这样写:
const fnCurried = (fn) => (b) => (...rest) => fn(ctx,...rest);
然而,如果我们只是使用它,那么我们还没有在任何地方提供上下文。这就是我们可以创建另一个名为 createCtx()
的函数的地方,该函数将为我们返回上述 fnCurried 函数,同时关闭提供的 ctx
:
const createCtx = ctx => fn => b => (...rest) => fn(ctx,...rest);
const fnCurried = createCtx(ctx);
someFn("something",fnCurried(fn));
createCtx
函数允许我们传入上下文,然后它为我们返回 fnCurried
,一旦调用就可以将其传递给 someFn