The ES6 specification introduces block-level functions, allowing function declarations within blocks. Understanding their semantics is critical for effective programming.
Setting | Visible Outside Block | Hoisted | Hoisting Scope | Temporal Dead Zone |
---|---|---|---|---|
Non-strict, No Web Extensions | No | No | N/A | N/A |
Strict, No Web Extensions | No | Yes | Block Level | Yes |
Non-strict, With Web Extensions | Yes | Yes | Function Level | Before Block |
Strict, With Web Extensions | Yes | Yes | Function Level | Before Block |
"Strict mode" in this context refers to the strictness of the function or script in which the block containing the function declaration appears, not the function itself. "web extensions" apply only to sloppy (non-strict) code with "sane" function appearance (no name collisions).
In pure ES6 (without "web extensions"), function declarations in blocks have consistent semantics regardless of strictness. They are hoisted to the top of the block and behave like regular function declarations.
With "web extensions," sloppy mode introduces additional semantics. A function declaration within a block is hoisted to the top of the enclosing function as a var declaration, and the function object is assigned to this variable when the function declaration is evaluated.
This results in two bindings for the same identifier: one function-scoped (visible outside the block) and one block-scoped (visible only within the block). The function-scoped binding is initialized with undefined until the function is declared, at which point it is assigned the function object.
Before the function declaration is encountered in block execution, the function-scoped binding is undefined and accessing it will throw an exception.
The above is the detailed content of How Do ES6 Block-Level Functions Behave in Strict and Non-Strict Modes, with and without Web Extensions?. For more information, please follow other related articles on the PHP Chinese website!