JavaScript 格式:大括号必须与 if/function/etc 关键字在同一行吗?
我们的公司政策规定,在 PHP 中,左大括号应单独成行以提高可读性,以便它们可以与右大括号对齐;因此:
if (true)
{
...
}
但在 JS 中,它们应该保持在同一行,以防浏览器错误解释它时出现问题。
if (true) {
...
上面的斜体部分是合理的担忧吗?
PS - 我怀疑这个问题已经在这里被问过,但我还没有找到与我完全匹配的问题。抱歉,如果它在那里但我没有找到它。
Possible Duplicate:
why results varies upon placement of curly braces in javascript code
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)
{
...
}
but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.
if (true) {
...
Is the above italic part a legitimate concern?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这在某些极端情况下很重要。
问题不在于“浏览器错误地解释它”。根据 ECMAScript 规范,这种狡猾的行为是正确的。不表现出这种行为的 JavaScript 实现将不符合规范。
一个例子。这个函数被破坏了:
它应该返回一个对象,但实际上什么也没返回。 JavaScript 是这样解释的:
Yes, it matters in certain corner cases.
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:
It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:
JS 中的解释,通常是当你的行没有分号时,它默认添加在行尾。为了避免这种情况并增加可读性,大括号通常与 IF、WHILE、Function 等添加在同一行。
据我所知,JS 中的此功能称为隐式分号插入。
The interpretation in JS, is usually when you have line without semi-colon, it is by default added at the end of line. To avoid such things and to increase readability, the braces are usually added on same line as IF, WHILE, Function etc.
This feature in JS is referred to as implicit semicolon insertion as far as I know.