In Javascript, when is it necessary to assign a named function to a variable?

后端 未结 3 1609
夕颜
夕颜 2020-12-11 03:15

In the online REPL of Babel JS (http://babeljs.io/repl/), when I type in :

let a = (x) => x+1

It will be transpiled to:

         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 04:15

    If you write:

    function a(x) { }
    

    then the function is hoisted to the top of the enclosing scope, and a becomes available immediately at parse time within the entire scope.

    However, when you write:

    var a = function a(x) { }
    

    then var a will not have a defined value in the enclosing scope until this line is actually executed.

    However, within that function, a different a will exist as a locally scoped reference to the function itself.

    By using the let a = function ... construct Babel is being more consistent with the latter form, ensuring that a is assigned at run time to a (named) function expression instead of using a parse time function declaration.

提交回复
热议问题