Look at some source framework (uncompressed) when occasionally see them give expression to add function function name.
For example, the following code:
// 添加函数名
setTimeout(function foo() {
console.log('foo');
}, 1000);
// 不给函数表达式看起来更简洁
setTimeout(function () {
console.log('foo');
}, 1000);
In fact, the function name is added to the function expression is a best practice, there are several reasons below:
1, if the code error function name can quickly locate the error location, otherwise anonymous function 栈追踪
does not show a meaningful function names, difficult to debug.
2, no function name, the function would like to quote their own need to rely on already obsolete arguments.callee
. There is a classic example of this is the use of removeEventListener()
required unbundling event function, that is, itself.
3, function names can improve the readability \ understandability of code, a bunch of anonymous functions makes the code becomes confusing.