Do standalone JavaScript blocks have any use?

岁酱吖の 提交于 2019-12-06 03:17:32

问题


The MDN article on JavaScript blocks gives this example:

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

As you can see JavaScript doesn't have block scope. So are there any good use cases for standalone blocks in JavaScript?

By "standalone" I mean not paired with a control flow statement (if, for, while, etc.) or a function.


回答1:


Short answer: ...not really.

The only use I know for them is labels:

myBlock: {
    // stuff
    if (something) break myBlock // jump to end of block
    // more stuff
    if (somethingElse) continue myBlock // jump to beginning of block
    // blah blah blah, more stuff
}

(almost like a goto, better watch out for the raptors)

Needless to say, this is a very bad idea. So basically, nothing; just don't use them.

(side note: a do { /* stuff */ if (something) break; /* stuff */ } while (false) could do the same thing)




回答2:


ES2015 introduces block scoping with let and const, so standalone blocks become useful for limiting the scope of variables:

{
  let privateValue = 'foo';
}

console.log(privateValue); // -> ReferenceError

In contrast to var:

{
  var privateValue = 'foo';
}

console.log(privateValue); // -> "foo"

let and const are implemented in the latest versions of all major browsers (including IE11).

  • let compatibility table
  • const compatibility table


来源:https://stackoverflow.com/questions/17939230/do-standalone-javascript-blocks-have-any-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!