简体   繁体   中英

How to call this function in Javascript?

How to call this function in Javascript? As it takes n as its outer function's parameter and it also needs another parameter i in its function inside, but how to call it?

function foo(n) { 
  return function (i) { 
           return n += i } }

调用函数的返回值:

foo(1)(2);

It a classic closure example: it does return a function which has access to the n variable.

var counter = foo(0);
counter(1); // 1
counter(2); // 3
counter(5); // 8

This is a function that returns a function. Often you would want a reference to that function, Like this

 foofn = foo(7);
 result = foofn(7);

You could also just call the function right away

 result = (foo(7))(7);

What the function does? Well that wasn't really your question...

This is the way we usually use JavaScript closures, first function creates a scope to keep the n variable safe to be used in the inner function:

var n = 11;
var myfunc = foo(n);

now you can call your myfunc function, with a simple i argument, whereas it uses n without you needing to pass it directly to your function:

myfunc(10);

so if you want to just call it, once it is created, you can do: foo(11)(10);

But in these cases we don't usually call them like this, they are usually supposed to be used as a callback or something like it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM