gpt4 book ai didi

javascript - 为什么 block 作用域最初不是在 JavaScript 中实现的?

转载 作者:IT王子 更新时间:2023-10-29 02:50:51 25 4
gpt4 key购买 nike

我已经阅读并通过自己的经验发现,JavaScript 没有 block 作用域。假设以这种方式设计语言是有原因的,您能向我解释一下那是什么原因吗?

我在 Google 和此处四处查看,但我发现的帖子只是重申 JS 具有函数作用域而不是 block 作用域,而没有解释原因。我很想知道为什么会这样。

最佳答案

将我的评论转换为答案

创建者的选择:我在推特上发布了 Brendan 并获得了 following answer :

@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.


也就是说,这里有一些相关的要点:

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.

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

letconst 声明的变量被提升,但它们以相同的方式初始化为 undefined var 是。因此,在赋值之前引用 letconst 声明的变量会引发 ReferenceError。

在同一 block 范围内重新声明同一变量会引发语法错误。

关于javascript - 为什么 block 作用域最初不是在 JavaScript 中实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17311693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com