首先我们先把jQuery看成了一个类,这样好理解一些。
那么jQuery.extend(),是就是为jQuery这个类扩展方法的。比如:
(function($) {
$.extend({
methods1 : function() {
alert('我是第一个扩展方法!!');
},
methods2 : function() {
alert('我是第二个扩展方法!!');
}
});
})(jQuery);
之后在js中调用:
$(document).ready(function() {
$.methods1();
$.methods2();
});
然后
就能调用执行这个方法了!
二,jQuery.fn.extend()
jQuery源码中有这样写:
jQuery.fn = jQuery.prototype,
那就是说
jQuery.fn.extend拓展的是jQuery对象(原型(实例化))的方法,看代码:
<span style="color: rgb(51, 51, 51);">;(function($) {
</span><span style="color:#990000;background-color: rgb(255, 255, 51);">$.fn.extend({</span><span style="color:#333333;">
methods1 : function() {
alert('我是第一个扩展方法!!');
},
methods2 : function() {
alert('我是第二个扩展方法!!');
}
});
})(jQuery);</span>
<span style="color:#333333;"><span style="font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;">调用的时候:</span>
</span>
<span style="color:#333333;"><span style="font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;"></span></span><pre name="code" class="javascript" style="font-size: 16px; line-height: 28px; text-align: justify; color: rgb(51, 51, 51);"><span style="font-family:Microsoft Yahei, 微软雅黑, arial, 宋体, sans-serif;">$(document).ready(function() {
</span><span style="font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif;"> </span><span style="background-color: rgb(255, 204, 51);"><span style="font-family:Microsoft Yahei, 微软雅黑, arial, 宋体, sans-serif;">$.("#id1").methods1();
</span><span style="font-family:Microsoft Yahei, 微软雅黑, arial, 宋体, sans-serif;"></span></span><pre name="code" class="javascript"><span style="font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; background-color: rgb(255, 204, 51);"><span> </span>$.(".abc").methods2();</span>
});
jQuery.extend()这个方法,主要是用来拓展个全局函数啦,例如$.ajax()这种,要不就是拓展个选择器啦,例如$.fn.each(),当选择器用。
大部分插件都是用jQuery.fn.extend()。