Function hoisting and the return statement

一个人想着一个人 提交于 2021-02-19 06:22:11

问题


I would expect this (reduced for the sake of example) function to run without a hitch, but it fails on account of fn2 is not defined:

void function(){
    var var1 = fn1();
    var var2 = fn2();

    function fn1(){};

    return function fn2(){};
}();

How does the return statement exclude the function expression for fn2 from hoisting?


回答1:


Only a function created with a function declaration is hoisted. The function in return function fn2(){}; is created with a (named) function expression so is not hoisted.

How a function is evaluated is dependent on context. Any function within a statement (such as a return statement) is parsed as a function expression. Another example is the use of parentheses in IIFEs: the parentheses act as a grouping operator, ensuring that the contents of the parentheses are evaluated as an expression.

Lots of information about this can be found in Kangax's excellent article:

http://kangax.github.io/nfe/



来源:https://stackoverflow.com/questions/21405327/function-hoisting-and-the-return-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!