Dangerous implications of Allman style in JavaScript

旧城冷巷雨未停 提交于 2019-11-26 00:55:59

问题


I cannot remember where, but recently I passed a comment where the user told that 1TBS is more preferred than Allman in JavaScript and said Allman has dangerous implications in JavaScript.

Was it a valid statement? If so, why?


回答1:


return cannot have LineTerminator after it so:

return
{


};

is treated as return; (return undefined) instead of return {}; (return an object)

See the rules for Automatic Semicolon Insertion (ASI) for more.




回答2:


It is a valid statement.

Because JavaScript's engines have what's called ASI (Automatic Semicolon Insertion) which inserts a semicolon if necessary at lines returns. The "if necessary" is ambiguous; sometimes it works and sometimes doesn't. See the rules.

So, as said in the other answers:

return
{
};

// Is read by the JavaScript engine, after ASI, as:
return; // returns undefined
{ // so this is not even executed
};

So it's not recommended for return statements.

However, if your guidelines recommend the Allman style for function declarations, it's perfectly fine. I know some that do.




回答3:


I think it depends on the statement. For example a return statement might be broken if opening brace is on new line. More info here.




回答4:


return {
    a: "A",
    b: "B"
};

// vs.

return // Semicolon automatically inserted here! Uh oh!
{
    a: "A",
    b: "B"
}


来源:https://stackoverflow.com/questions/11247328/dangerous-implications-of-allman-style-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!