The main benefit for naming the function
is in allowing it to be self-referential, especially for recursion:
If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard arguments.callee property.
var math = {
'factorial': function factorial(n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
};
That is, without it having to be aware of its holding object and referencing property name, which can change:
// a contrived and hopefully unrealistic example
function foo() {
this.bar = function () {
return this.bar;
};
}
console.log(new foo().bar()); // Function
console.log(new foo().bar.call({})); // undefined, `{}` doesn't have a `bar`
As previously noted, it's an available solution to the partial "outlawing" of arguments.callee
:
Note: You should avoid using arguments.callee()
and just give every function (expression) a name.
Warning: The 5th edition of ECMAScript forbids use of arguments.callee()
in strict mode.