Function that returns another function returning itself

0

First of all, I am asking this out of sheer curiosity, it has no real application where this would be useful (or do I know?).

I know that it is possible to make a function return another function, and that the returned function can be a parameter, that is.

function a(b) {
    return b();
}

So, if I pass a function inside function "a", it returns the return of the function that was used as parameter after its execution. Exemplifying again:

function foo() {
    return 'bar';
}

console.log(a(foo)); // printa 'bar'
Until then, okay. However, and when I try to invoke the function a within itself?

a(a); // erro

I've tried, and the answer is an error reporting b is not a function .

I wanted to understand how / why this occurs. In my head he should get into an infinite processing cycle, and lock, or something. Did I let something happen?

    
asked by anonymous 30.08.2018 / 16:48

1 answer

3

You let a single detail go by. When you call the a function it is necessary to pass a parameter, which does not happen here:

a(a); // o a de dentro não recebe o parâmetro

Then when a executes return b(); - execution of the internal a, without parameter - you get the error because parameter b is not defined, since it was not passed.

    
30.08.2018 / 17:49