简体   繁体   English

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

[英]In the Google analytics tracking code, why do they use a closure

Why in the google analytics tracking code, do they wrap these lines in a closure? 为什么在谷歌分析跟踪代码中,他们是否将这些行包装在一个闭包中?

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

Wouldn't it work the same without the parent closure? 如果没有父关闭,它会不会一样?

It would work the same, but it could easily break other scripts on your page, if you've declared a variable with an identifier used in the Google code. 如果您声明了一个带有Google代码中使用的标识符的变量,它的工作方式也相同,但它可能很容易破坏页面上的其他脚本。

By wrapping the declaration in a closure, the variables are scoped to the anonymous function and don't leak to the global scope. 通过将声明包装在闭包中,变量的范围限定为匿名函数,并且不会泄漏到全局范围。

For example, consider this example with the new scope: 例如,请考虑使用新范围的此示例:

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

And this example without it: 没有它的这个例子:

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

It would work the same as long as there were no global scope variables defined using the same name. 只要没有使用相同名称定义的全局范围变量,它就会起作用。 Wrapping the code in a closure places it in its own scope so that it is independent from any other code on the page. 将代码包装在闭包中会将其置于其自己的作用域中,以使其独立于页面上的任何其他代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM