Do inner functions in JavaScript get hoisted? How do the scoping rules apply to them?

后端 未结 2 1151
春和景丽
春和景丽 2020-12-03 20:43

I thought that JavaScript doesn\'t have block scope, but function scope, and that declarations are hoisted from their block to the top of their parent functions.

How

相关标签:
2条回答
  • 2020-12-03 20:58

    The declaration of inner is hoisted to the top of the outer function. However, its value is only set if a == 1.

    When outer() is called with a different value, the call to inner(456) fails as inner is still set to undefined.

    0 讨论(0)
  • 2020-12-03 21:11
    if (…) {
        function …() {            
            …
        }
    }
    

    is invalid ECMAScript. Function declarations must be on the top level of function or program bodies, inside of blocks their behaviour is implementation-dependent. Firefox does execute this function statement conditionally, other browsers do hoist it like a normal function declaration. Move it outside the if-statement, or assign a function expression.

    0 讨论(0)
提交回复
热议问题