IT story

JavaScript 이외의 다른 언어가 중괄호 시작 위치 (같은 줄과 다음 줄)에 차이가 있습니까?

hot-time 2020. 9. 3. 23:43
반응형

JavaScript 이외의 다른 언어가 중괄호 시작 위치 (같은 줄과 다음 줄)에 차이가 있습니까?


오늘 저는 JavaScript patterns O'Reilly 책을 무작위로 읽는 동안 흥미로운 점을 발견했습니다 (참조 용 27 페이지).

Javascript에서는 경우에 따라 중괄호 시작 위치가 다르면 차이가 있습니다.

function test_function1() {
    return
    {
        name: 'rajat'
    };
}

var obj = test_function1();
alert(obj);  //Shows "undefined"

동안

function test_function2() {
    return {
        name: 'rajat'
    };
}

var obj = test_function2();
alert(obj); //Shows object

JSfiddle 데모

다른 언어에도 그러한 행동이 있습니까? 그렇다면 내 습관을 확실히 바꿔야 할 것 같다 .. :)

저는 주로 PHP, C, C ++, Java 및 루비에 관심이 있습니다.


문을 구분하기 위해 세미콜론 (대신 개행)에 의존하지 않는 모든 언어는 잠재적으로이를 허용합니다. Python을 고려하십시오 .

>>> def foo():
...   return
...   { 1: 2 }
... 
>>> def bar():
...   return { 1: 2 }
... 
>>> foo()
>>> bar()
{1: 2}

Visual Basic 에서 비슷한 경우를 구성 할 수는 있지만 VB가 값을 배치 할 수있는 위치에있어 매우 제한적이기 때문에 어떻게해야하는지 알 수 없습니다. 그러나 정적 분석기가 도달 할 수없는 코드에 대해 불평하지 않는 한 다음은 작동합니다.

Try
    Throw New Exception()
Catch ex As Exception
    Throw ex.GetBaseException()
End Try

' versus

Try
    Throw New Exception()
Catch ex As Exception
    Throw
    ex.GetBaseException()
End Try

언급 한 언어에서 Ruby 는 동일한 속성을 가지고 있습니다. PHP, C, C ++ 및 Java는 단순히 줄 바꿈을 공백으로 버리고 명령문을 구분하기 위해 세미콜론을 필요로하기 때문이 아닙니다.

다음은 Ruby의 Python 예제에 해당하는 코드입니다.

>> def foo
>>   return { 1 => 2 }
>> end
=> nil
>> def bar
>>   return
>>   { 1 => 2 }
>> end
=> nil
>> foo
=> {1=>2}
>> bar
=> nil

JavaScript 인터프리터는 자동으로 ;각 줄 끝에를 추가합니다 (일부 예외는 있지만 여기에 들어 가지 않습니다 :).

So basically the issue is not the braces' location (which here represent an object literal, not a code block as in most languages), but this little "feature" that forces your first example to return ; => undefined. You can check out the behavior of return in the ES5 spec.

For other languages that have similar behavior, check out Konrad's answer.


Most certainly. Google's go programming language exhibits a very similar behavior (albeit with different effects). As explained there:

In fact, what happens is that the formal language uses semicolons, much as in C or Java, but they are inserted automatically at the end of every line that looks like the end of a statement. You don't need to type them yourself.

..snip...

This approach makes for clean-looking, semicolon-free code. The one surprise is that it's important to put the opening brace of a construct such as an if statement on the same line as the if; if you don't, there are situations that may not compile or may give the wrong result. The language forces the brace style to some extent.

Secretly, I think Rob Pike just wanted an excuse to require the One True Brace Style.


The answer to that question is fairly easy. Any language that has "automatic semicolon insertion" might be in trouble on that line. The problem with this

return
{
     name: 'rajat'
};

..is that the js engine will insert a semicolon after the return; statement (and therefore, return undefined). This example is a good reason to open curly brackets always on the right side and never on the left side also. Since you already correctly noticed, if there is a curly bracket in the same line, the interpretator will notice that and can't insert a semicolon.


FWIW, JSLint reports several warnings with that syntax:

$ jslint -stdin
function foo(){
  return
  { x: "y" };
}
^D
(3): lint warning: unexpected end of line; it is ambiguous whether these lines are part of the same statement
  return
........^

(3): lint warning: missing semicolon
  { x: "y" };
..^

(3): lint warning: unreachable code
  { x: "y" };
..^

(3): lint warning: meaningless block; curly braces have no impact
  { x: "y" };
..^

(3): lint warning: use of label
  { x: "y" };
.....^

(3): lint warning: missing semicolon
  { x: "y" };
...........^

(3): lint warning: empty statement or extra semicolon
  { x: "y" };
............^


0 error(s), 7 warning(s)

The first language where I came across this was awk (which also has its share of syntax "oddities"; optional semi colons, string concatenation using only whitespace and so on...) I think the DTrace designers, which based the D syntax loosely on awk, had enough sense to NOT copy these features, but I can't remember off the top of my head. A simple example (counting the number of ENTITY tags in a DTD, from my Mac):

$ cat printEntities.awk 
# This prints all lines where the string ENTITY occurs
/ENTITY/ {
  print $0
}
$ awk -f printEntities.awk < /usr/share/texinfo/texinfo.dtd | wc -l
     119

If this little script instead were written with the brace on a line of its own, this is what would happen:

$ cat printAll.awk 
# Because of the brace placement, the print statement will be executed
# for all lines in the input file
# Lines containing the string ENTITY will be printed twice,
# because print is the default action, if no other action is specified
/ENTITY/
{ 
   print $0 
}
$ awk -f printAll.awk < /usr/share/texinfo/texinfo.dtd | wc -l
     603
$ /bin/cat < /usr/share/texinfo/texinfo.dtd | wc -l
     484
$ 

참고URL : https://stackoverflow.com/questions/9191776/does-any-other-language-other-than-javascript-have-a-difference-between-brace-st

반응형