2012-10-31 22 views
6

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

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

如果没有父关闭,它不会工作吗?

+3

这是为了避免使用'ga'和's'变量来污染全局名称空间。 – AKX

回答

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

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