为什么块作用域最初没有在 JavaScript 中实现? [英] Why was block scope not originally implemented in JavaScript?
问题描述
我已经阅读并通过自己的经验发现,JavaScript 没有块作用域.假设语言被设计成这样是有原因的,你能向我解释一下是什么原因吗?
I have read, and discovered through my own experience, that JavaScript doesn't have a block scope. Assuming that the language was designed this way for a reason, can you explain to me what is that reason?
我在谷歌和这里环顾四周,但我发现的帖子只是重申 JS 有一个函数作用域而不是块作用域,没有解释原因.我很想知道为什么会这样.
I've looked around on Google and here, but the posts I have found just reiterate that JS has a function scope and not block scope, without explaining why. I'm curious to know why this is actually the case.
推荐答案
将我的评论转换为答案
创作者的选择:我在推特上给 Brendan 发了推文并得到了以下答案:
Choice of the creator: I tweeted Brendan and got the following answer:
@mplungjan 10 天没有为块范围留出时间.90 年代中期的许多脚本语言"也几乎没有范围.后来长大了.
@mplungjan 10 days did not leave time for block scope. Also many "scripting languages" of that mid-90s era had few scopes & grew more later.
<小时>
也就是说,这里有一些相关的要点:
That said, here are some relevant points:
重要提示:ECMAScript2015(第 6 版)之前的 JavaScript 没有块作用域.块中引入的变量的作用域是包含函数或脚本,并且设置它们的效果在块本身之外持续存在.换句话说,块语句不引入作用域.尽管独立"块是有效的语法,但您不希望在 JavaScript 中使用独立块,因为如果您认为它们在 C 或 Java 中执行此类块,则它们不会执行您认为它们所做的事情.
Important: JavaScript prior to ECMAScript2015 (6th edition) does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.
- 解决方法
- ECMAScript 2015 (ES6)一>
我们可以通过创建新函数并立即调用它们来人为地引入作用域
we can artificially introduce scopes by creating new functions and immediately invoking them
let
和 const
声明的变量被提升,但它们未以相同的方式初始化为 undefined
var
是.因此,在赋值之前引用 let
或 const
声明的变量会引发 ReferenceError.
let
and const
declared variables are hoisted but they are not initialized to undefined
in the same way var
is. Hence, referencing a let
or const
declared variable before its value is assigned raises a ReferenceError.
在同一块范围内重新声明同一变量会引发 SyntaxError.
Redeclaration of the same variable in the same block scope raises a SyntaxError.
这篇关于为什么块作用域最初没有在 JavaScript 中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!