Why use named function expressions?

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

Named function expression (NFE) :

var boo = function boo () {
  alert(1);
};

Anonymous function expression :

var boo = function () {
  alert(1);
};

And both of them can be called with boo(); . I really can't see why/when I should use anonymous functions and when I should use Named Function Expressions. What difference is there between them?


In the case of the anonymous function expression, the function is anonymous — literally, it has no name. The variable you're assigning it to has a name, but the function does not. (Update: That was true through ES5. As of ES2015 [aka ES6], often a function created with an anonymous expression gets a true name, read on...)

Names are useful. Names can be seen in stack traces, call stacks, lists of breakpoints, etc. Names are a Good Thing™.

You do have to beware of named function expressions in older versions of IE (IE8 and below), because IE mistakenly creates two completely separate function objects at two completely different times (more in my blog article Double take). If you need to support IE8, it's probably best to stick with anonymous function expressions or function declarations, but avoid named function expressions.

As of ES2015, though, a lot of "anonymous" function expressions create functions with names, and this was predated by various modern JavaScript engines being quite smart about inferring names from context. In ES2015, your anonymous function expression results in a function with the name boo . This is strewn throughout the spec rather than being defined in one place with a bunch of rules: Search for occurrences of "SetFunctionName", currently found in:

  • §12.2.6.9 (property initializer semantics)
  • §12.14.4 (assignment operator semantics)
  • §12.14.5.2 and §12.14.5.4 (destructuring assignment semantics)
  • §13.3.1.4 ( let and const declaration semantics)
  • ...and a bunch of other places.
  • The short version is basically any time an anonymous function expression appears on the right-hand side of something like an assignment or initialization, like:

    var boo = function() { /*...*/ };
    

    (or it could be let or const rather than var ), or

    var obj = {
        boo: function() { /*...*/ }
    };
    

    or

    doSomething({
        boo: function() { /*...*/ }
    });
    

    (those last two are really the same thing), the resulting function will have a name ( boo , in the examples).

    There's an important, and intentional, exception: Assigning to a property on an existing object:

    obj.boo = function() { /*...*/ }; // <== Does not get a name
    

    This was because of information leak concerns raised when the new feature was going through the process of being added; details in my answer to another question here.


    Naming functions is useful if they need to reference themselves (eg 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)


    If a function is specified as a Function Expression, it can be given a name.

    It will only be available inside the function (except IE8-).

    This name is intended for a reliable recursive function call, even if it is written to another variable.

    Note that with the Function Declaration this can not be done. This "special" internal function name is specified only in the Function Expression syntax.

    var f = function sayHi(name) {
      alert( sayHi ); // Inside the function you can see the function code
    };
    
    alert( sayHi ); // (Error: undefined variable 'sayHi')
    

    In addition, the NFE (Named Function Expression) name can not be overwritten:

    var test = function sayHi(name) {
      sayHi = "тест"; // try to redefine
      alert( sayHi ); // function... (redefinition is unsuccessful )
    };
    
    test();
    
    链接地址: http://www.djcxy.com/p/17266.html

    上一篇: Javascript函数声明之间的区别

    下一篇: 为什么使用命名函数表达式