Вопрос

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?

Это было полезно?

Решение

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/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top