这两个 JavaScript 函数有什么区别?
我一直在研究一些 jQuery 插件的工作原理,我看到以下内容作为整个插件的闭包,
$(function(){
// plugin code here
});
(function($){
// plugin code here
})(jQuery);
这两个插件有什么区别?
I've been looking at how some jQuery plugins work and I've seen the following acting as a closure around the whole plugin
$(function(){
// plugin code here
});
(function($){
// plugin code here
})(jQuery);
What is the difference between these two ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个是 jQuery DOM Ready 函数定义,而第二个是函数闭包,它在解析后立即运行,并以
jQuery
对象作为参数执行。第一个通常用在页面上,当您希望在
页面加载所有文档元素都存在(文档已准备好)时执行某些操作时。第二个通常与插件一起使用,因为它创建了一个闭包,以便您可以在其中定义外部代码无法访问的私有属性。
The first one is a jQuery DOM Ready function definition, while the second one is a function closure that runs immediately when it's parsed and is executed with
jQuery
object as a parameter.The first one is usually used on your pages when you want something to execute when
your page loadsall document elements exist (document is ready).The second one is usually used with plugins because it creates a closure so you can define privates in it that won't be accessible to outside code.
第一个是
jQuery.ready
的快捷方式。仅当 DOM 完全准备好被操作时,它才会调用您提供的函数(通常不是在该脚本首次运行时;因此会回调)——例如,当您可以通过 ID 安全地查找元素时,或者通过 CSS 选择器,添加新元素等。第二个立即运行该函数(可能在 DOM 准备好操作之前)并将
jQuery
对象作为名为$。在该函数中,您可以安全地假设
$
引用 jQuery 对象,而如果没有这个,如果您使用jQuery.noConflict
将$
释放回 jQuery 之前曾经拥有它的任何对象(可能是 Prototype)已加载。当您使用$
编写大量代码,但随后发现必须与 Prototype 或其他也想使用$
的东西共存时,此技术非常有用。您只需将所有代码放入匿名函数中即可。如果你愿意,你可以一起做这两件事:
The first one is a shortcut for
jQuery.ready
. It calls the function you give it only when the DOM is fully ready to be manipulated (which it typically isn't when this script first runs; hence the callback) — e.g., when you can safely look for elements by their ID, or by CSS selector, add new elements, etc., etc.The second runs the function immediately (potentially before the DOM is ready to be manipulated) and passes the
jQuery
object in as a parameter named$
. Within the function, you can safely assume that$
references the jQuery object, whereas without this you can't if you're usingjQuery.noConflict
to release the$
back to whatever used to have it (perhaps Prototype) before jQuery was loaded. This technique is useful when you have a lot of code written with$
, but then find you have to co-exist with Prototype or something else that also wants to use$
. You just put all of your code within the anonymous function.You can do both things together if you like: