为什么块作用域最初没有在 JavaScript 中实现? [英] Why was block scope not originally implemented in JavaScript?

查看:19
本文介绍了为什么块作用域最初没有在 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.

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