JavaScript格式化:必须使用大括号与if / function / etc关键字保持一致。 [英] JavaScript formatting: must braces be on the same line as the if/function/etc keyword?

查看:295
本文介绍了JavaScript格式化:必须使用大括号与if / function / etc关键字保持一致。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我们制定的公司政策规定,在 PHP 中,大括号应该在自己的行上,以便可读性,关闭支撑;因此:

  if(true)
{
...
}

但是在 JS 中,它们应该保持在同一行,浏览器有不正确的解释问题

  if(true){
...

上面的斜体部分是否合理?



PS - 我怀疑这个问题已经在这里问过了,但是我还没有找到和我的完全一致的问题。道歉,如果它在那里,我没有找到它。

解决方案

是的,

问题不在于浏览器不正确地解释它。根据ECMAScript规范,狡猾行为是正确的。一个没有出现这种行为的JavaScript实现将不符合规范。



一个例子。这个函数被打破:

$ p $ function returnAnObject {
return
{
foo:'test '
};
}

它应该返回一个对象,但实际上什么都不返回。 JavaScript解释如下:

 函数returnAnObject {
return;
{
foo:'test'
};
}


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.

解决方案

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:

function returnAnObject {
    return
    {
        foo: 'test'
    };
}

It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:

function returnAnObject {
    return;
    {
        foo: 'test'
    };
}

这篇关于JavaScript格式化:必须使用大括号与if / function / etc关键字保持一致。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆