Why use named function expressions?

后端 未结 5 1635
忘了有多久
忘了有多久 2020-11-22 01:33

We have two different way for doing function expression in JavaScript:

Named function expression (NFE):

var boo = function boo () {         


        
5条回答
  •  花落未央
    2020-11-22 02:34

    Naming functions is useful if they need to reference themselves (e.g. for recursive calls). Indeed, if you are passing a literal function expression as an argument directly to another function, that function expression cannot directly reference itself in ES5 strict mode unless it is named.

    For example, consider this code:

    setTimeout(function sayMoo() {
        alert('MOO');
        setTimeout(sayMoo, 1000);
    }, 1000);
    

    It would be impossible to write this code quite this cleanly if the function expression passed to setTimeout were anonymous; we would need to assign it to a variable instead prior to the setTimeout call. This way, with a named function expression, is slightly shorter and neater.

    It was historically possible to write code like this even using an anonymous function expression, by exploiting arguments.callee...

    setTimeout(function () {
        alert('MOO');
        setTimeout(arguments.callee, 1000);
    }, 1000);
    

    ... but arguments.callee is deprecated, and is outright forbidden in ES5 strict mode. Hence MDN advises:

    Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

    (emphasis mine)

提交回复
热议问题