为什么块范围最初并未在JavaScript中实现? [英] Why was block scope not originally implemented in JavaScript?

查看:145
本文介绍了为什么块范围最初并未在JavaScript中实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读并通过自己的经验发现JavaScript没有块范围。假设语言是出于某种原因而设计的,那是什么原因?

I have read, and discovered through my own experience, that JavaScript doesn't have block scope. Assuming that the language was designed this way for a reason, what is that reason?

我在谷歌和这里看过,但我发现的帖子只是重申JS有功能范围而不是阻止范围,没有解释原因。我很想知道为什么会出现这种情况。

I've looked around on Google and on here, but the posts I have found just reiterate that JS has 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:

  • Block statement

重要说明:JavaScript没有块范围。块中引入的变量的范围限定为包含函数或脚本,设置它们的效果将持续超出块本身。换句话说,块语句不引入范围。虽然独立块是有效的语法,但您不希望在JavaScript中使用独立块,因为如果您认为它们在C或Java中执行类似块的操作,则它们不会按照您的想法执行操作。

Important: JavaScript 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.




  • 一种解决方法

    • a workaround

    • 我们可以人为地介绍范围通过创建新函数并立即调用它们

      we can artificially introduce scopes by creating new functions and immediately invoking them




      • ECMAScript 2015(ES6)

        • ECMAScript 2015 (ES6)
        • 声明的变量被提升到封闭块的开头。因此,在分配值之前引用 let 声明的变量会引发ReferenceError。

          let declared variables are not hoisted to the beginning of the enclosing block. Hence, referencing a let declared variable before its value is assigned to raises a ReferenceError.

          重新声明相同的变量在相同的块范围内引发一个SyntaxError。

          Redeclaration of the same variable in the same block scope raises a SyntaxError.

          这篇关于为什么块范围最初并未在JavaScript中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆