자바 스크립트 변수 정의 : 쉼표 대 세미콜론
세미콜론이 아닌 변수 그룹을 선언 할 때 쉼표를 사용할 때의 차이점 및 / 또는 장점은 무엇입니까?
예를 들면 :
var foo = 'bar', bar = 'foo';
대
var foo = 'bar';
var bar = 'foo';
var
첫 번째 예제에서 첫 번째 변수에 키워드 를 지정하면 모든 변수에 걸쳐 지속되므로 둘 다 범위와 관련하여 동일한 최종 결과를 생성한다는 것을 알고 있습니다. 그것은 단지 개인적인 취향입니까, 아니면 어느 쪽이든 수행하면 성능상의 이점이 있습니까?
성능상의 이점은 없으며 개인적인 선택과 스타일의 문제입니다.
첫 번째 버전은 더 간결합니다.
최신 정보:
전송되는 데이터의 양에 관해서는 물론 적을수록 좋지만 var
실제 영향을 보려면 엄청나게 많은 제거 된 선언 이 필요합니다 .
축소를가 로 첫 번째 예는, 그러나, 더 나은 축소를 위해 도움이됩니다 무언가로 언급 된 다니엘 Vassallo이 코멘트에 지적, 좋은의 minifier은 자동으로 당신을 위해 어쨌든, 그래서 그 점에 영향을주지 않고 무엇이든지 할 것입니다.
Crockford와 다른 사람들을 읽은 후 쉼표로만 변수를 연결하기 시작했습니다. 그런 다음 나중에 쉼표로 변수 정의에서 멈추지 않는 Chrome DevTools 디버거에 정말 짜증이났습니다. 디버거의 경우 쉼표로 연결된 변수 정의는 단일 문이며 여러 var 문은 디버거가 중지 할 수있는 여러 문입니다. 따라서 다음에서 다시 전환했습니다.
var a = doSomethingA,
b = doSomethignB,
c = doSomethingC;
에:
var a = doSomethingA;
var b = doSomethignB;
var c = doSomethingC;
이제 디버거 문제를 해결하는 이점은 말할 것도없고 두 번째 변형이 훨씬 더 깔끔하다는 것을 알게되었습니다.
축소자가 있기 때문에 "전선을 통한 코드 감소"인수는 설득력이 없습니다.
나는 var-per-variable
표기법을 선호합니다 .
var a = 2
var b = 3
다른 comma-instead-of-another-var
표기법에는 다음과 같은 세 가지 단점이 있기 때문입니다 .
1. 유지하기 어렵다
다음 코드를 고려하십시오.
var a = 1,
b = mogrify(2),
c = 3
하지만 mogrify는 무엇을합니까? b를 인쇄하여 알아 봅시다 :
var a = 1,
b = mogrify(2),
console.log(b)
c = 3
물건을 부수다
2. 읽기 어렵다
줄 구걸의 var는 새로운 변수가 시작될 것임을 명확하게 전달합니다.
var get_all_unicorn_promise = db.get_all_unicorns((unicorn) => {
unicorn.legs.map((leg) => {
leg.log('yes')
})
}).sort(),
c = 3
도대체 c = 3
거기서 뭐하는거야?
3. 일관성이 없음
이걸 고려하세요:
var a = 1,
b = 2,
c = 3
함께 var-per-variable
모든 선언 동일한 구조를 따릅니다. 함께 comma-instead-of-another-var
첫 번째 변수에 다른 사람보다 다른 방식으로 선언됩니다. for 사이클 내에서 첫 번째 변수를 이동하기로 결정한 경우 선언 중간에 var를 추가해야합니다.
Other than preference, it seems like majority of notable projects use the var-per-variable
notation
I agree with the other answerers that this is mainly a matter of personal style. But to bring an "Authoritative" opinion into the discussion, this is what Douglas Crockford says on the website of the popular JSLint tool:
But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be enforced with the
onevar
option.
As others have noted, it is a style preference. JSLint might tell you to only have one var
per function (if you use the "Good Parts"). Thus if using JSLint to check your code (not a bad idea, IMHO), you'll end up using the first format more than the latter.
On the other hand, the same author, Douglas Crockford, says to put each variable in its own line in his coding conventions. So you may want to uncheck the "All one var
per function" checkbox in JSLint if you use it. ;-)
I don't think there's any noticeable difference, as far as I'm concerned it's just personal preference.
I hate having multiple var declarations so I usually do:
var
one
,two
,three
,four
;
As it's shorter and arguably more readable, no var
noise to look at.
Since I don't see any references to it, here is a link to the ECMA-262 specification, which is the underlying spec for JavaScript. The grammar from that page says:
12.2 Variable Statement
Syntax
VariableStatement :
var VariableDeclarationList ;
VariableDeclarationList :
VariableDeclaration
VariableDeclarationList , VariableDeclaration
VariableDeclarationListNoIn :
VariableDeclarationNoIn
VariableDeclarationListNoIn , VariableDeclarationNoIn
VariableDeclaration :
Identifier Initialiseropt
VariableDeclarationNoIn :
Identifier InitialiserNoInopt
Initialiser :
= AssignmentExpression
InitialiserNoIn :
= AssignmentExpressionNoIn
What you can glean from this is using commas or not doesn't matter. Either way, it ends up being parsed as a VariableDeclaration
and is treated exactly the same. There should be no difference to how the script engine treats the two declarations. The only differences would be ones already mentioned in other answers - saving more space and practically immeasurable differences in the amount of time it takes to apply the grammar to find all the VariableDeclarations
when the script is compiled.
The first saves a few characters--so there is a very small saving in terms of the JS filesize and therefore bandwidth consumption. The only time this would become noticable would be in extreme cases.
I prefer the second version (each has its own var
). I think that's because I come from a C++ background. In C++, you can declare variables like you do in your first example, but it is frowned upon (it easily leads to mistakes when you're trying to create pointers that way).
If you are minifying your javascript, there is a fairly large benefit:
var one, two, three, four;
becomes
var a, b, c, d;
Where as
var one;
var two;
var three;
var four;
becomes
var a;
var b;
var c;
var d;
That's an additional three instances of var
, which can add up over time.
See The "A List Apart" article series "Better Javascript Minification" Part 1 and Part 2
참고URL : https://stackoverflow.com/questions/3781406/javascript-variable-definition-commas-vs-semicolons
'program story' 카테고리의 다른 글
배열 대신 객체를 반환하는 이유는 무엇입니까? (0) | 2020.09.22 |
---|---|
Visual Studio : "빌드 실패, 마지막 성공 여부"다시 활성화 (0) | 2020.09.22 |
std :: system_clock과 std :: steady_clock의 차이점은 무엇입니까? (0) | 2020.09.22 |
Iframe 콘텐츠가로드 된시기 감지 (크로스 브라우저) (0) | 2020.09.22 |
공식 JavaScript 참조가없는 이유는 무엇입니까? (0) | 2020.09.22 |