深入了解JavaScript作用域和作用域链
作者: ljianshu创建于 2019年3月15日更新于 2022年11月13日
Block-level scope can be created by using the let and const declarations. Variables declared with let and const cannot be accessed outside the specified block. Block-level scope is created in the following cases:
- Inside a function
- Inside a code block (enclosed by a pair of brackets) The syntax for let declarations is the same as for var declarations. You can basically use let to replace var for variable declarations, but it will limit the scope of the variable to the current block. Block-level scope has the following characteristics:
- Variable declarations are not promoted to the top of the block Let/const declarations are not promoted to the top of the current block, so you need to manually place the let/const declarations at the top so that the variables are available within the entire block.
- Re-declaration is prohibited If an identifier has already been defined within the block, then using the same identifier for let declaration within the same block will cause an error. For example: var count = 30; let count = 40; // Uncaught
内容来源: ljianshu/Blog