Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

javascript - JS Function With Two Parentheses and Two Params

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 know how to write one that takes two params like so:

function add(a, b) {
  return a + b;
}

add(10,10); // returns 20

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

Any help is appreciated. Literally scratching my head over this.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...