In currying why does the outside, initiating function appear to be the innermost function?

*爱你&永不变心* 提交于 2020-01-16 19:02:07

问题


In the simple, 2 layer currying example below the word dog is passed into the y argument.

"use strict";

function layer2(x) {
    return function(y) {
        return console.log(x, y);
    }
}

var layer1 = layer2('cat');

layer1('dog');

I know it works this way and I can reliably reproduce this. However I can't understand the mechanics of why this works. If I made a 100 layer example layer 1 would be the innermost function and the pattern would work outwards from that point. What piece of basic mechanics causes this? Thanks so much for any input!


回答1:


In short, lexical scoping is what makes this possible. See, layer2 function in your example returns another function that has two variables in its scope:

y - its own argument
x - parameter passed into `layer2` function

The key point here is that once you store that returned function, x value is set and will never change. Again, in terms of your example, function stored in layer1 variable - result of layer2('cat') - has x name bound to 'cat' string value.




回答2:


It's simple. When you call layer2('cat') it will return the function:

function(y) {
  return console.log(x, y);
}

Now, layer1('dog') returns function call return console.log(x,y); on which x is received already in a call layer2('cat'), and y is being called from function(y).

Here's a very good read blog https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/ which will help you further.



来源:https://stackoverflow.com/questions/47936053/in-currying-why-does-the-outside-initiating-function-appear-to-be-the-innermost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!