Name for anonymous functions

12

In some sample code for frameworks, libs, etc. I checked that the anonymous functions were passed with a name for them.

minhaFuncao(function minhaFuncaoAnonima() {
    // ...
});

What is the purpose of naming anonymous functions? Is it any pattern that should be followed?

    
asked by anonymous 30.03.2015 / 20:04

2 answers

16

There are two goals:

  • Recursion: is a way to enable function expressions are recursive. The defined name for these functions is only available within themselves, and can be used for recursive calls. Anonymous function expressions do not allow recursion.

  • Debugging: In the most commonly used JS debuggers, these functions are identified by the name in the call stack rather than as anonymous function . This helps you better see which snippet of code is running.

  • The article quoted by TobyMosque, Named function expressions demystified is the great reference on the subject . However, it is already somewhat outdated, and I believe that the compatibility issues it points out do not apply to modern browsers anymore (IE, 10+ versions, maybe 9). It pays to read the article link for more details, it's really great (as well as others from the same author, such as Understanding delete ).

        
    30.03.2015 / 20:16
    13

    This is called Named Function Expression . If the function is recursive, that is to call itself, this is very useful and respects the normal scope rules.

    For example:

    var number = 12;
    var numberFactorial = (function factorial(number){
        return (number == 0) ? 1 : number * factorial(number - 1); // aqui a função chama-se a sí própria
    })(number);
    console.log(numberFactorial); // 479001600
    

    So the function can call itself to find the result. And note that the factorial function will not stay in the global scope: link

    Example: link

        
    30.03.2015 / 20:16