JS Function With Two Parentheses and Two Params

后端 未结 4 1550
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 09:16

I\'m trying to understand how a function works that is run with two parentheses and two parameters. Like so:

add(10)(10); // returns 20

I k

4条回答
  •  一个人的身影
    2020-12-15 09:46

    How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?

    You can almost do that, but I'm struggling to think of a good reason to.

    Here's how: You detect how many arguments your function has received and, if it's received only one, you return a function instead of a number — and have that function add in the second number if it gets called:

    function add(a,b) {
      if (arguments.length === 1) {
        return function(b2) { // You could call this arg `b` as well if you like,
          return a + b2;      // it would shadow (hide, supercede) the one above
        };
      }
      return a + b;
    }
    console.log(add(10, 10)); // 20
    console.log(add(10)(10)); // 20

    I said "almost" above because just because the add function received only one argument, that doesn't guarantee that the caller is going to call the result. They could write:

    var x = add(10);
    

    ...and never call the function that x now refers to.

提交回复
热议问题