【问题标题】:In the Google analytics tracking code, why do they use a closure在谷歌分析跟踪代码中,为什么他们使用闭包
【发布时间】:2012-10-31 08:00:01
【问题描述】:

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

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

如果没有父闭包,它的工作方式是否相同?

【问题讨论】:

  • 这是为了避免gas 变量污染全局命名空间。

标签: javascript closures


【解决方案1】:

它的工作原理相同,但如果您声明了一个带有 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);

【讨论】:

    【解决方案2】:

    只要没有使用相同名称定义的全局范围变量,它就可以正常工作。将代码包装在闭包中会将其置于自己的作用域中,使其独立于页面上的任何其他代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多