jquery开发juqery插件的步骤理解

jquery开发juqery插件的方法理解

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

 

jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法。

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

 

 

 

一、从面相对象角度理解两个方法

 

jQuery便是一个封装得非常好的类,比如我们用 语句 $("#btn1") 会生成一个 jQuery类的实例。

jQuery.extend(object); 为jQuery类添加添加类方法,可以理解为添加"静态方法"。可以在jquery环境下直接调用。

例如:

 

 

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

 

那么就可以像引用“静态方法”一样引用add方法:$.add(3,4); //return 7

 

看下jQuery.fn.extend的源码:

 

jQuery.fn = jQuery.prototype = {
   init: function( selector, context ) {//.... 
   //......
};
 

 

jQuery.fn.extend(object); 是对jQuery.prototype进得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。

例如:

 

$.fn.extend({ 
   alertWhileClick:function(){ 
       $(this).click(function(){
            alert($(this).val());        
        }); 
    }  
});

 

可以在实例上引用该方法:     

$("#input1").alertWhileClick(); //页面上为:<input id="input1" type="text"/>  

 

 

二、详细理解jQuery.extend方法用法

 

1、使用方法一:

extend(dest,src1,src2,src3...);

理解:

它的含义是将src1,src2,src3...合并到dest中,返回值为合并后的dest

例如:

var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})//{}作为dest,这样就不会改变dest的结构了

合并后的结果

result={name:"Jerry",age:21,sex:"Boy"}

2、使用方法二:省略dest

extend(src);

    A)$.extend(src)

    该方法就是将src合并到jquery的全局对象中去

 

        $.extend({
             hello:function(){alert('hello');}
        });

    就是将hello方法合并到jquery的全局对象中,使用方法:$.hello();

 

    B)$.fn.extend(src)

        该方法将src合并到jquery的实例对象中去

 $.fn.extend({
  hello:function(){alert('hello');}
 });

         就是将hello方法合并到jquery的实例对象中,使用方法:$(obj).hello();

         例如:

         $.extend({net:{}}); //这是在jquery全局对象中扩展一个net命名空间。

         $.extend($.net,{hello:function(){alert('hello');}});//这是将hello方法扩展到之前扩展的Jquery的net命名空间中去。

3、使用方法三:

extend(boolean,dest,src1,src2,src3...);

理解:第一个参数boolean代表是否进行深度拷贝,其余参数和前面介绍的一致,什么叫深层拷贝。

 

参考:

1、关于jquery.fn等 http://blog.sina.com.cn/s/blog_4ca246370100vnfb.html

2、jQuery.extend 函数详解 http://www.cnode.cn/article.asp?id=537