在Google分析跟踪代码中,为什么他们使用闭包

Jus*_*tin 6 javascript closures

为什么在谷歌分析跟踪代码中,他们是否将这些行包装在一个闭包中?

(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);
})();
Run Code Online (Sandbox Code Playgroud)

如果没有父关闭,它会不会一样?

Jam*_*ice 7

如果您声明了一个带有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);
})();
Run Code Online (Sandbox Code Playgroud)

没有它的这个例子:

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);
Run Code Online (Sandbox Code Playgroud)