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 } }
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 } }
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.