将jquery函数包装在闭包中有什么好处? [英] What is the benefit of wrapping a jquery function in a closure?
问题描述
您好,我一直在尝试将我对JQuery的知识提高到一个新的水平,到目前为止,我认为我已经理解了所有内容,但是当我尝试使用更高级的教程时,我注意到JQuery例程的几个实例被包裹在一个闭包中(见下文),但是,令我困惑的是它传递了一个$并返回了JQuery.我的问题是为什么?返回的JQuery我该怎么办?
Hi I've been busy trying to take my knowledge of JQuery to the next level, So far I think I've understood everything but as I've ventured onto more advanced tutorials I've noticed several instances where the JQuery routine is wrapped in a closure (see below) however, the thing that confuses me is that it passes a $ and returns JQuery. My question is why? what can I do with the returned JQuery?
我真的很感谢人们能为我提供的启发.
I'd really appreciate any light that people can shed on this for me.
(function($){
$(document).ready(function(){
var arr = $.map($("LI"), function(item, index){
while (index < 3)
{
return $(item).html();
}
return null;
});
$(document.body).append("<span>The first three authors are: " +
arr.join(", ") + "</span>");
});
})(jQuery);
谢谢.
Rob
推荐答案
这是一个自我调用的匿名函数(已声明并立即执行的未命名函数),它带有一个分配给参数$
的参数.传递给该参数的值为jQuery函数jQuery
.
It's a self invoking anonymous function (an un-named function that is declared and immediately executed) that takes one argument that gets assigned to the parameter $
. The value passed in for the argument is jQuery
, the jQuery function.
这样做是为了使速记$
可以在函数范围内用于表示jQuery.由于该函数内部的所有代码都在该函数的范围内,因此这是一种很好的模式,可以自我包含代码并且不污染全局名称空间.
This is done so that the shorthand $
can be used inside the scope of the function to mean jQuery. Since all of the code inside of the function is in the scope of the function, it's a nice pattern for self containing the code and not polluting the global namespace.
这也是允许您在函数内使用jQuery的$
速记的一种不错的模式-可能会为$
速记(window.$
)分配其他内容,如果您在一页上使用多个库.通过使用模式,您仍然可以使用$
引用函数中的jQuery
对象以使其更加熟悉和简洁.
It's also a nice pattern for allowing you to use the $
shorthand for jQuery inside of the function - it could be the case that the $
shorthand (window.$
) is assigned something else, as can happen if you use multiple libraries on one page. By using the pattern, you can still use $
to reference jQuery
object in the function for familiarity and terseness.
这篇关于将jquery函数包装在闭包中有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!