Why use named function expressions?

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

    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-).

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

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

    In addition, the NFE (Named Function Expression) name CAN be overwritten with the Object.defineProperty(...) method as follows:

    var test = function sayHi(name) {
      Object.defineProperty(test, 'name', { value: 'foo', configurable: true });
      alert( test.name ); // foo
    };
    
    test();
    

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

提交回复
热议问题