問題描述
可能重復(fù):
為什么在javascript中放置花括號(hào)時(shí)結(jié)果會(huì)有所不同代碼
我們的公司政策規(guī)定,在 PHP 中,左大括號(hào)應(yīng)該在自己的行中以提高可讀性,以便它們可以與右大括號(hào)對(duì)齊;因此:
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 中它們應(yīng)該保持在同一行,以防瀏覽器錯(cuò)誤解釋它出現(xiàn)問題.
but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.
if (true) {
...
上述斜體部分是否合理?
PS - 我懷疑這里已經(jīng)有人問過這個(gè)問題,但我沒有找到與我的完全匹配的問題.抱歉,如果它在那里,但我沒有找到它.
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.
問題不在于瀏覽器錯(cuò)誤地解釋它".根據(jù) ECMAScript 規(guī)范,狡猾的行為是正確的.沒有表現(xiàn)出這種行為的 JavaScript 實(shí)現(xiàn)將不符合規(guī)范.
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.
一個(gè)例子.這個(gè)函數(shù)壞了:
An example. This function is broken:
function returnAnObject {
return
{
foo: 'test'
};
}
它應(yīng)該返回一個(gè)對(duì)象,但實(shí)際上什么也沒返回.JavaScript 是這樣解釋的:
It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:
function returnAnObject {
return;
{
foo: 'test'
};
}
這篇關(guān)于JavaScript 格式:大括號(hào)必須與 if/function/etc 關(guān)鍵字在同一行嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!