[英]Can someone explain what the syntax means when defining a jQuery plugin?
I am reading up on creating custom jQuery plugins and am a little confused as to the meaning of the following syntax: 我正在阅读有关创建自定义jQuery插件的内容,并且对以下语法的含义有些困惑:
(function($){
$.fn.truncate = function() {
return this.each(function() {
});
};
})(jQuery);
I understand that function($) is an anonymous function that accepts the $. 我知道function($)是一个接受$的匿名函数。 I just don't quite understand why this function is wrapped in brackets and how the following sets of brackets with jQuery in them...work.
我只是不太明白为什么将此函数包装在方括号中,以及以下带有jQuery的方括号是如何工作的。
The following parameters with jQuery are just executing the anonymous function and passing in jQuery as the $ parameter. jQuery的以下参数只是执行匿名函数,并将jQuery作为$参数传递。 This ensures that $ = jQuery just incase window.$ doesn't equal jQuery.
这样可以确保$ = jQuery仅以window为例。$不等于jQuery。
Here is a rewrite of the code that might make more sense: 这是对代码的重写,可能更有意义:
function myFunc($) {
$.fn.truncate = function() {
return this.each(function() {
});
}
myFunc(jQuery);
The surrounding parentheses create an anonymous function to which the $
symbol references the global jQuery
object. 圆括号创建一个匿名函数,
$
符号引用该函数引用全局jQuery
对象。
$.fn.truncate
- This means that you are extending the jQuery
object to include a new function called truncate
. $.fn.truncate
这意味着您正在扩展jQuery
对象,以包括一个名为truncate
的新函数。
Usage $( '#someElement' ).truncate();
用法
$( '#someElement' ).truncate();
It is not safe to assume that $
is owned by the jQuery library. 假定
$
由jQuery库拥有是不安全的。 Some other javascript libraries/users may/do use that identifier for other purposes. 其他一些JavaScript库/用户可能/确实将该标识符用于其他目的。 However,
jQuery
is always the jQuery library (barring any evildoers). 但是,
jQuery
始终是jQuery库(禁止任何邪恶的行为者)。
This anonymous function handily and safely exposes the $
shortcut as jQuery by making it a local parameter to the anonymous function. 该匿名函数通过将
$
快捷方式作为匿名函数的本地参数,方便安全地将$
快捷方式公开为jQuery。 Since parameters will override any globals only for the scope of a function this will not affect any other user/library code outside of it. 由于参数仅会在函数范围内覆盖全局变量,因此不会影响函数外的任何其他用户/库代码。
Finally, where the anonymous function is executed jQuery
is passed in as the first paramter to fill $
. 最后,在执行匿名函数的地方,将
jQuery
作为第一个填充$
参数传入。
So when boiled down, this is just a shortcut taken by plugin developers so that they can safely and reliably use $
; 因此,归根结底,这只是插件开发人员所采取的捷径,以便他们可以安全可靠地使用
$
;。 if you don't mind using jQuery
everywhere instead then this is totally optional. 如果您不介意在所有地方使用
jQuery
,那么这完全是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.