Google 코드에서 사용 된 식별자로 변수를 선언 한 경우에도 동일하게 작동하지만 페이지의 다른 스크립트가 쉽게 손상 될 수 있습니다.
클로저에 선언을 래핑하면 변수의 범위가 익명으로 지정되고 전역 범위로 누출되지 않습니다. 그것없이
var ga = "something important for my script"; // Not overwritten in this scope
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
그리고 예 :
예를 들어, 새로운 범위로이 예제를 고려 정의 된 전역 변수는 없었다으로
var ga = "something important for my script"; // Overwritten!
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
전역 이름 공간을'ga' 및's' 변수로 오염시키지 않기 위해서입니다. – AKX