Javascript中孤独代码块的目的是什么? [英] What's the purpose of lonely code blocks in Javascript?

查看:137
本文介绍了Javascript中孤独代码块的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,您可以拥有孤独的代码块,即没有的代码块,如果 function 或像他们之前的那样,在代码中任意放置,如下所示:

In Javascript, you can have lonely code blocks, that is, code blocks without an if, function or something like that preceding them, placed arbitrarily in the code, like this:

var a = 3,
b = 4;
{
  a = 50;
  b = 50;
}
alert(a + b); //alerts 100

我知道其他一些语言都有这个(我认为C ++有),他们使用它用于作用域控制:在孤立的代码块内声明的变量不能在它之外访问。但由于Javascript具有函数作用域而不是块作用域,因此必须使用自执行函数(function(){})()来实现相同的效果。

I know some other languages have this (I think C++ does), and they use it for scope control: variables declared inside the lonely code block cannot be accessed outside of it. But since Javascript has function scope rather than block scope, you have to use a self-executing function (function(){})() to acheive the same effect.

这个结构是否有用途?你见过有人用它吗?规格是否提到了?这只是语法的一个副作用,它有一些关于代码块的一般规则吗?

Is there a purpose for this construct? Have you ever seen anybody use it? Does the spec mention it? Is this just a side effect of the grammar having some sort of general rule about code blocks?

推荐答案

正如我在google搜索后发现的那样我的答案标签如何与声明一起使用这不是一个循环?,孤独的代码块可以与标签相关:

As I found out after googling my answer for How are labels used with statements that are not a loop?, the lonely code blocks can be related to labels:

myLabel:
{
    for(x in y) {
        break myLabel;
    }
}

不仅会突破循环,而且会突破外部代码块也是如此。

Will break out not only of the loop, but of the outer code block as well.

这篇关于Javascript中孤独代码块的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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