为什么结果因大括号放置而异? [英] Why do results vary based on curly brace placement?
问题描述
为什么下面的代码片段来自这个文章,由于花括号的位置只有一个变化,会产生不同的结果吗?
Why do the code snippets below, taken from this article, produce different results due to only a single change in the placement of curly braces?
当大括号 {
在新行上, test()
返回 undefined
,并且没有 - 它破了:undefined显示在警报中。
When the opening curly brace {
is on a new line, test()
returns undefined
, and "no - it broke: undefined" is displayed in the alert.
function test()
{
return
{ /* <--- curly brace on new line */
javascript: "fantastic"
};
}
var r = test();
try {
alert(r.javascript); // does this work...?
} catch (e) {
alert('no - it broke: ' + typeof r);
}
当大括号与返回
在同一行时, test()
返回一个对象,并提醒神奇。
When the brace is on the same line as return
, test()
returns an object, and "fantastic" is alerted.
function test()
{
return { /* <---- curly brace on same line */
javascript: "fantastic"
};
}
var r = test();
try {
alert(r.javascript); // does this work...?
} catch (e) {
alert('no - it broke: ' + typeof r);
}
推荐答案
这是JavaScript的一个陷阱:自动分号插入。不以分号结尾但可能是语句结尾的行会自动终止,因此您的第一个示例看起来很有效:
That's one of the pitfalls of JavaScript: automatic semicolon insertion. Lines that do not end with a semicolon, but could be the end of a statement, are automatically terminated, so your first example looks effectively like this:
function test()
{
return; // <- notice the inserted semicolon
{
javascript: "fantastic"
};
}
另见 Douglas Crockford的JS风格指南,其中提到了分号插入。
See also Douglas Crockford's JS style guide, which mentions semicolon insertion.
在你的第二个例子中,你返回一个对象(由花括号构建),其属性为 javascript
,其值为fantastic
,实际上与此相同:
In your second example you return an object (built by the curly braces) with the property javascript
and its value of "fantastic"
, effectively the same as this:
function test() {
var myObject = new Object();
myObject.javascript = "fantastic";
return myObject;
}
这篇关于为什么结果因大括号放置而异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!