JavaScript 格式:大括号必须与 if/function/etc 关键字在同一行吗?
可能重复:
为什么在javascript中放置花括号时结果会有所不同代码
我们的公司政策规定,在 PHP 中,左大括号应该在自己的行中以提高可读性,以便它们可以与右大括号对齐;因此:
We have company policies that dictate that in PHP opening curly braces should be on their own lines for readability and so that they can line-up with the closing brace; thus:
if (true)
{
...
}
但在 JS 中它们应该保持在同一行,以防浏览器错误解释它出现问题.
but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.
if (true) {
...
上述斜体部分是否合理?
PS - 我怀疑这里已经有人问过这个问题,但我没有找到与我的完全匹配的问题.抱歉,如果它在那里,但我没有找到它.
PS - I suspect that this question has been asked on here already, but I've not found a question that exactly matches mine. Apologies if it's there and I didn't find it.
推荐答案
是的,这在某些极端情况下很重要.
Yes, it matters in certain corner cases.
问题不在于浏览器错误地解释它".根据 ECMAScript 规范,狡猾的行为是正确的.没有表现出这种行为的 JavaScript 实现将不符合规范.
And the problem isn't with "browsers incorrectly interpreting it". The dodgy behaviour is correct according to the ECMAScript specifications. A JavaScript implementation that didn't exhibit this behaviour would not be spec-compliant.
一个例子.这个函数坏了:
An example. This function is broken:
function returnAnObject {
return
{
foo: 'test'
};
}
它应该返回一个对象,但实际上什么也没返回.JavaScript 是这样解释的:
It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:
function returnAnObject {
return;
{
foo: 'test'
};
}
相关文章