本文介绍了JS函数以相反的顺序组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从简单的函数组合开始

const fa = (x => (x + "a"));
const fb = (x => (x + "b"));
fb(fa('x'))

我玩耍了,获得了以下代码段,该代码段返回"xba"而不是"xab".

I played around and I obtained the following code snippet which returns 'xba' instead of 'xab'.

有人可以解释为什么吗?

Can someone explain why?

const fa = next => x => next(x + "a");
const fb = next => x => next(x + "b");

console.log(fb(fa(y => y))('x'));

推荐答案

让我们分解一下:

const _fa = fa(y => y)
// _fa = x => (y => y)(x + "a")

为避免混淆两个 x ,我们将其命名为 x1

To avoid confusing the two x let's name it as x1

// _fa = x1 => (y => y)(x1 + "a")

现在是:

Now fb would be:

// fb = next => x2 => next(x2 + "b")

如果我们用 fa(y => y)(即 _fa )调用 fb ,则将 next _fa :

If we call fb with fa(y => y) (ie. _fa), we substitute next with _fa:

_fb = fb(fa(y => y))
// _fb = x2 => (x1 => (y => y)(x1 + "a"))(x2 + "b")

现在让我们使用参数 x2 ='x'来评估 _fb :

Now lets evaluate _fb with the argument x2 = 'x':

// _fb = (x1 => (y => y)(x1 + "a"))("x" + "b")
// _fb = (x1 => (y => y)(x1 + "a"))("xb")

注意 x1 =>(y => y)(x1 +"a")可以简化为 x1 =>x1 +"a" .现在我们有:

Notice how x1 => (y => y)(x1 + "a") can be simplified to x1 => x1 + "a". Now we have:

// _fb = (x1 => x1 + "a")("xb")

现在让我们使用参数 x1 ="xb"

// _fb = "xb" + "a"
// _fb = "xba"

这篇关于JS函数以相反的顺序组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:06