了解 jQuery 插件的骨架
在一个网站,我发现了下面的代码来制作一个jQuery插件:
(function($){
// Our code here...
})(jQuery);
我不明白上面的代码是如何实现的作品。我的理解是,代码立即执行,因为 function(){}()
中的最后一个 ()
。所以整个代码表明这是一个立即运行的匿名函数。
但我不明白为什么包装需要传递 jQuery
而其内部需要传递 $
。
据我了解, $
是 jQuery
的别名,含义几乎相同。这里的$
和jQuery
是什么意思?整个代码作为 jQuery 插件如何工作?
At a website, I found the following code to make a jQuery plugin:
(function($){
// Our code here...
})(jQuery);
I don't understand how the code above works. What I understand is that the code executes immediately because the very last ()
in function(){}()
. So the entire code says that is an anonymous function that is run immediately.
But I don't understand why the wrapping needs to pass jQuery
and that inside it needs $
to be passed.
From my understanding, $
is an alias to jQuery
, meaning practically the same. What is the meaning of $
and jQuery
here? How does the overall code work as a jQuery plugin?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
jQuery 是实际参数。 $ 是形式参数。你完全可以这样写:
原因之一是方便——它很短。您可能会在 noConflict 模式下与其他库一起使用 jQuery。也许一直输入
jQuery
很麻烦,或者其他插件遵循不好的做法并使用$
而不是jQuery
。无论哪种方式,您都可以使用像上面这样的自调用函数来解决问题。jQuery is the actual parameter. $ is the formal parameter. You could very well write:
One reason is convenience - it's short. You might be using jQuery in noConflict mode with other libraries. Maybe typing
jQuery
all the time is a hassle, or other plugins are following bad practices and using$
instead ofjQuery
. Either ways, you can use a self-calling function like the one above to solve the problem.您在函数中传递别名
$
,以便它实际上始终引用 JQuery。如果某个页面中包含一些其他库(例如也使用$
的原型),您的代码不会中断并且可以正常工作。You pass the alias
$
in function so that it will always refter to JQuery actually. If there are some other libraries included in a certain page such as prototype which also uses$
, your code won't break and will work fine.为了最大限度地兼容其他库,jQuery 提供了
.noConflict()
。这将从全局命名空间中删除
$
别名,以便其他库可以根据需要使用它。如果您不希望您的插件与
.noConflict()
一起使用,则没有必要。使用闭包还允许您不使用
var
污染“全局范围”In order to be maximally compatible with other libraries as well, jQuery offers
.noConflict()
. This removes the$
alias from the global namespace so another library could use it if you want.If you don't want your plugin to work with
.noConflict()
it's not necessary.Using the closure also allows you to not pollute the "global scope" with
var
'sGnarf 提出了 vars 的全局范围污染,我也会添加函数。
您可能想使用如下辅助函数:
这样内部函数 foobalizeTheFrobmaster() 就完全隐藏在我们的闭包中。
Gnarf brought up global scope pollution of vars, I would add of functions as well.
You might want to use a helper function like:
This way the internal function
foobalizeTheFrobmaster()
is completely hidden in our closure.