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

时间:2012-10-31 08:00:01

标签: 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);
})();

没有父关闭会不会有相同的效果吗?

2 个答案:

答案 0 :(得分: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);
})();

这个没有它的例子:

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);

答案 1 :(得分:3)

只要没有使用相同名称定义的全局范围变量,它就会起作用。将代码包装在一个闭包中会将它放在自己的范围内,这样它就可以独立于页面上的任何其他代码。

相关问题