【发布时间】:2012-01-06 17:03:37
【问题描述】:
我在处理 jQuery 插件时特别看到过这种代码。有人可以解释一下这是做什么的吗?
(function(){
//Stuff goes here....
}());
【问题讨论】:
-
这项技术主要与范围变量有关,因此您无需在全局范围内声明一堆变量,但您不一定需要函数或对象方法。
标签: javascript
我在处理 jQuery 插件时特别看到过这种代码。有人可以解释一下这是做什么的吗?
(function(){
//Stuff goes here....
}());
【问题讨论】:
标签: javascript
他们在大括号之间用 Javascript 定义一个函数(这里的东西是要执行的代码),然后使用打开和关闭的括号立即执行它。这与 JQuery 无关,它只是 javascript 中的一个匿名函数。 function(){} 返回一个函数对象,然后由打开和关闭的括号执行。
【讨论】:
i 这样的一次性变量。在Javascript中有很多这样写的一次性函数,尤其是处理回调请求
通常,当您在 JavaScript 中遇到这种模式时,就是有人试图利用模块模式。该模式通常被认为是保护您自己的代码不与您可能在您的页面上使用的其他库(如果您在网页中编码)发生不良交互的好方法。
见:
http://yuiblog.com/blog/2007/06/12/module-pattern/
请注意,示例代码中匿名函数声明的开头和结尾的圆括号实际上不是必需的。 Paul Irish,在下面链接的视频中,认为这些通常被包含在内,以提醒任何阅读代码的人,代码是自包含的,而不仅仅是程序代码。
我的意思是:
function(){
//Stuff goes here....
}();
和以下一样有效:
(function(){
//Stuff goes here....
}());
还有:
(function(){
//Stuff goes here....
})();
还有:
!function(){
//Stuff goes here....
}();
等等。
Paul Irish 在此视频中谈到了这种模式:
http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
【讨论】:
:)
该模式主要用于控制变量的可见性。例如,
var SomeObject = (function() {
var test = "Some val"; // this will be a private variable
function testFunction() { // this will be a private function
}
return {
anotherVariable : "Hello", // this will be a public variable
anotherFunction : function() {
// this will be a public function that can be called from the object
// and can access the private properties 'test' and 'testFunction'
}
}
})();
阅读有关模块模式的更多信息here。
jQuery 插件经常做这样的事情:
(function($){
$.fn.pluginName = function() {
// plugin code here
};
})(jQuery);
这样做是为了确保 jQuery 和其他 JS 库之间没有冲突。
希望这会有所帮助。
【讨论】: