问题
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