Why use named function expressions?

后端 未结 5 1582
忘了有多久
忘了有多久 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:26

    You should always use named function expressions, that's why:

    1. You can use the name of that function when you need recursion.

    2. Anonymous functions doesn't help when debugging as you can't see the name of the function that causes problems.

    3. When you do not name a function, later on its harder to understand what it's doing. Giving it a name makes it easier to understand.

    var foo = function bar() {
        //some code...
    };
    
    foo();
    bar(); // Error!
    

    Here, for example, because the name bar is used within a function expression, it doesn't get declared in the outer scope. With named function expressions, the name of the function expression is enclosed within its own scope.

提交回复
热议问题