我正在阅读有关函数范围与块范围的信息。并了解到 Javascript 具有函数范围。
现在当我想到它时,我所知道的所有语言都有函数范围。我真的不知道任何具有块范围的语言。你们能指点我一些具有块范围的语言吗?
还有一个疑问,在一种具有块作用域的语言中,如何访问循环块之外的 for 循环的索引值?拥有块作用域有什么好处?
谢谢。
我正在阅读有关函数范围与块范围的信息。并了解到 Javascript 具有函数范围。
现在当我想到它时,我所知道的所有语言都有函数范围。我真的不知道任何具有块范围的语言。你们能指点我一些具有块范围的语言吗?
还有一个疑问,在一种具有块作用域的语言中,如何访问循环块之外的 for 循环的索引值?拥有块作用域有什么好处?
谢谢。
ALGOL 60 was the first to use the block scope followed by many like C, C++, C#
...etc
Check out the Block scope section of this Wikipedia page.
Advantage of having Block scope
Blocks are primarily used for control flow, such as with if, while, and for loops, and in these cases block scope means the scope of variable depends on the structure of a function's flow of execution. However, languages with block scope typically also allow the use of "naked" blocks, whose sole purpose is to allow fine-grained control of variable scope. For example, an auxiliary variable may be defined in a block, then used (say, added to a variable with function scope) and discarded when the block ends, or a while loop might be enclosed in a block that initializes variables used inside the loop that should only be initialized once.
“在 JavaScript 中,块没有作用域。只有函数才有作用域。除非复合语句要求,否则不要使用块。”
道格拉斯·克罗克福德说