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

后端 未结 28 2334
长发绾君心
长发绾君心 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 14:46

        let add = (a, b) => b === undefined ? add.bind(null, a) : a + b;
        console.log(add(10, 5)); //15
        console.log(add(10)(5)); //15
    

    /* In the arrow function which returns a ternary expression, we explicitly check if the 2nd argument(b) is passed in or not b==="undefined" in both cases of add(a,b) and add(a)(b).

    1. if "undefined" in the case of add(a)(b) it uses "add.bind(null,a)", the "bind" method is associated with all functions(functions are objects) which creates a new function that is returned by the arrow function and passes in:
      • "null" for the first argument "the context its binding to which allows it to default to the window object"
      • "a" the second argument to be returned with the new function.
      • so when the new function is called at this point add(a)>>>(b) "b" is no longer undefined so the ternary switches to a+b.
    2. If not b==="undefined" in the case of add(a, b) the ternary switches to a+b */

提交回复
热议问题