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

后端 未结 2 1158
春和景丽
春和景丽 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 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.

提交回复
热议问题