admin管理员组文章数量:1312727
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
.
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
.
- 2 Taken from the same article: "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." I would take their word for it on this one if I were you. – BoltClock Commented Jul 30, 2013 at 5:57
- @BoltClock I'm still curious if they have a use, whether it's a good one or not. – Web_Designer Commented Jul 30, 2013 at 5:58
- @BoltClock While that's true, the OP seems to be looking for specific scenarios where people think "Well, I've found block statements are great for ______". I'm not sure there are any, but still :) – Ian Commented Jul 30, 2013 at 5:59
2 Answers
Reset to default 8ES2015 introduces block scoping with let
and const
, so standalone blocks bee 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
patibility tableconst
patibility table
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)
本文标签: Do standalone JavaScript blocks have any useStack Overflow
版权声明:本文标题:Do standalone JavaScript blocks have any use? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741893535a2403441.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论