How can I make var a = add(2)(3); //5 work?

后端 未结 28 2427
长发绾君心
长发绾君心 2020-11-27 14:11

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I\

28条回答
  •  臣服心动
    2020-11-27 15:01

    Here we use concept of closure where all the functions called inside main function iter refer and udpate x as they have closure over it. no matter how long the loop goes , till last function , have access to x.

    function iter(x){    
    return function innfunc(y){
    //if y is not undefined
    if(y){
    //closure over ancestor's x
    x = y+x;
    return innfunc;
    }
    else{
    //closure over ancestor's x
    return x;
        }
      }
    }
    

    iter(2)(3)(4)() //9 iter(1)(3)(4)(5)() //13

提交回复
热议问题