Name for anonymous functions

Asked

Viewed 151 times

12

In some example code frameworks, libs, etc. I found that anonymous functions were passed with a name to the same.

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

What is the purpose of naming anonymous functions? It is some standard that should be followed?

2 answers

16


There are two objectives:

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

  2. Debugging: Us debuggers of most commonly used JS, these functions are identified by the name on the call stack, rather than as Anonymous Function. This helps you see better which chunk of code is running.

The article cited 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 problems it points out no longer apply to modern browsers (in the case of IE, versions 10+, maybe 9). It is worth reading the linked article for more details, it is really excellent (as well as others of the same author, as the Understanding delete).

13

That’s 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 be called itself to find the result. And notice that the factorial function will not stay in the global scope: http://jsfiddle.net/xgoo0w02/

Example: http://jsfiddle.net/z9knLsmm/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.