여기 발췌이다에서 JQuery와 소스 코드 (1.7.1) 시작 :jQuery 소스가 변수 할당을 위해 쉼표 연산자를 사용하는 이유는 무엇입니까?
// Define a local copy of jQuery
var jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// ...continues...
// [[Class]] -> type pairs
class2type = {};
코드는 가변 할당하는 일련의 모든 콤마 연산자에 의해 결합이있다. the comma operator을 이해하면 앞뒤의 표현식을 평가하고 후행 표현식의 값을 반환합니다.
변수 할당 체인이 아무 것도 지정되지 않았기 때문에 코드가 작동 방식을 변경하지 않고 쉼표 대신 세미콜론으로 다시 쓸 수 있다는 사실을 알게되었습니다. 예 :
// Define a local copy of jQuery
var jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
}; /* <----- semicolon */
// Map over jQuery in case of overwrite
_jQuery = window.jQuery; /* <----- semicolon */
// Map over the $ in case of overwrite
_$ = window.$; /* <----- semicolon */
// ...and so on.
이 같은 세미콜론으로 다시 작성하는 경우 코드는 동일한 효과를겠습니까, 아니면 내가 뭔가를 놓친 거지?
이 일 때 동일한 효과가있는 경우 쉼표로 쓰는 이유는 무엇입니까? (나는 이유는 모르겠지만 내가, 예를 들어, 그 Crockford doesn’t like the comma operator (see near the bottom)을 알고있다.)
, 그는 (강조 광산 말한다) :, (쉼표) 연산자 - for 명령문의 제어 부분에서 매우 규칙적인 사용을 제외하고 쉼표 연산자의 사용을 피하십시오. (* 객체 리터럴, 배열 리터럴, * var 문 * 및 매개 변수 목록에 사용되는 쉼표 구분 기호 *에는 적용되지 않습니다.) – thirtydot
세미콜론을 사용하면 각 변수에 대해 var를 작성해야합니다. isn ' 그렇지? – Brij
@thirtydot : doh, 잡았다, 좋은 곳. 변수 선언 섹션에서 한 줄에 하나의 선언을 제안합니다. (분명히 그는 단지 선언하고 초기화하는 것보다 선언하는 것입니다.) –