jquery的$.extend和$.fn.extend作用及区别

jQuery为开发插件提拱了两个方法,分别是:

jQuery.fn.extend(object);

jQuery.extend(object);

jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法。可以理解为添加静态方法

jQuery.fn.extend(object);给jQuery对象添加方法。

 

$.extend({

  add:function(a,b){return a+b;}

});
$.add(3,4);  //return 7

fn 是什么东西

jQuery.fn = jQuery.prototype = {

   init: function( selector, context ) {//.... 

   //......

};

 jQuery.fn.extend拓展的是jQuery对象(原型的)的方法,对象是啥?就是类的实例化,例如   $("#abc")   这个玩意就是一个实例化的jQuery对象。

$.fn.extend({    
    
   alertWhileClick:function(){    
   
       $(this).click(function(){    
   
            alert($(this).val());    
        });    
    
    }    
    
});    
    
$("#input1").alertWhileClick(); //页面上为:<input id="input1" type="text"/> 

 $("#input1") 为一个jQuery实例,当它调用成员方法 alertWhileClick后,便实现了扩展,每次被点击时它会先弹出目前编辑里的内容。

 用一个或多个其他对象来扩展一个对象,返回被扩展的对象

var settings = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
jQuery.extend(settings, options); 
结果:settings == { validate: true, limit: 5, name: "bar" }

 jQuery.extend() 的调用并不会把方法扩展到对象的实例上,引用它的方法也需要通过jQuery类来实现,如jQuery.init(),

 而 jQuery.fn.extend()的调用把方法扩展到了对象的prototype上,所以实例化一个jQuery对象的时候,它就具有了这些方法

(function( $ ){
$.fn.tooltip = function( options ) {
};
//等价于
var tooltip = {
function(options){
}
};
$.fn.extend(tooltip) = $.prototype.extend(tooltip) = $.fn.tooltip
})( jQuery );
(function ($, plugin) {


})(jQuery, 'popup');

插件开发博客:http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html

原文地址:https://www.cnblogs.com/zhuiluoyu/p/4686368.html