Google 分析跟踪代码使用的技术是什么? [英] What's the technique that the Google analytics tracking code uses?
问题描述
Google Analytics 跟踪代码如下所示:
The Google Analytics tracking code looks like this:
(function() {
code
})();
他们对这些括号使用的技术是什么 - (stuff)()
- 被称为?它有什么作用?
What's the technique they are using with those brackets - (stuff)()
- called? What does it do?
我将 Google Analytics 代码放在页面上的关闭 head 标记之前,然后像这样在它周围放置一个 if 语句(我在上面包含了一个 Jquery cookie 插件):
I put the Google Analytics code before the closing head tag on my page and then put an if statement around it like this (I include a Jquery cookie plugin further up):
<script type="application/javascript">
if ($.cookie('allowcookies') == 'yes') {
analytics code
}
</script>
直到我在我的代码中使用相同的技术它才运行:
It didn't run until I used the same technique around my code:
(function() {if ($.cookie('allowcookies') == 'yes') {
analytics code
}
})();
为什么在我这样做之前它没有运行?为什么要追?
Why did it not run before I did that? Why did it run after?
推荐答案
(function() {
/* code */
}());
它通常被称为«自执行匿名函数 (¹)»(o «立即函数调用»),其主要用途是避免在全局(或外部)范围内创建变量.
It's commonly known as «self executed anonymous function (¹)» (o «immediate function invocation») and its main use is to avoid the creation of variables into the global (or in the outer) scope.
当您想创建一个只执行一次的函数时,它也可以用作快捷方式,而无需先用自己的标识符定义函数,然后很快进行函数调用.
It's also used as shortcut when you want to create a function to execute just once, without the need to first define the function with its own identifier and then soon make the function call.
它可能最终在作用域内使用,然后如果外部上下文(或其他引用)通过参数传递绑定,则它可能会创建一个闭包,例如
It may be eventually used inside a scope and then it may create a closure if the outer context (or other references) are binded through parameters passing, e.g.
/* outer scope */
(function(outerscope) {
element.onsomeevent = function() {
/* do something with outerscope */
};
}(this));
我用这个表达式做的另一个实际用途是当我需要创建一个函数时,当使用 new
关键字(而不是显式调用某些 new
code>init 方法).
Another practical use I make with this expression is when I need to create a function to be soon executed inside a constructor function when it is called with new
keyword (instead of an explicit call to some init
method).
(¹) —正如 Nicholas Zakas (O'Reilly, ISBN 978-1-449-32768-2) 页面 44 所著的Mantainable Javascript"一书所述,建议的表达式为 (function() {}())
,带有嵌套括号(即使 (function() {})()
仍然可以工作)
(¹) — as stated on book "Mantainable Javascript" by Nicholas Zakas (O'Reilly, ISBN 978-1-449-32768-2) page 44, the suggested expression is (function() {}())
, with nested parens (even if (function() {})()
will work anyway)
[...]为了让函数立即调用更明显,在函数[...]
[...]To make it obvious that immediate function invocation is taking place, put paretheses around the function[...]
另见立即函数调用语法
这篇关于Google 分析跟踪代码使用的技术是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!