【jquery】jquery插件的拓展方法

来源:互联网 发布:sip摄像机软件 编辑:程序博客网 时间:2024/06/06 14:15

1.类级别的拓展,即直接使用$就可以调用

      ·拓展格式:

     $.extend({           object//方法拓展     });
         ·栗子:

   window.onload = function(){            alert($.myAdd(4,5));        };   $.extend({            myAdd:function(x,y){                if(arguments.length != arguments.callee.length || typeof x != "number"||typeof y !="number"){                    return false;                }else{                    return x+y;                }            }        });


          ·这里为了防止变量污染,可以用如下方式扩展,一个匿名函数:等同于 var fn = function($){};fn(jQuery)

   (function($){   //定义JQuery的作用域,即私有作用域            $.extend({                myAdd:function(x,y){                    if(arguments.length != arguments.callee.length || typeof x != "number"||typeof y !="number"){                        return false;                    }else{                        return x+y;                    }                }            });        })(jQuery);
       ·扩展jquery方法时,如果有默认值default时的定义如下

window.onload = function(){    var options = {        x:3,        y:4    }    alert($.myAdd());//12    alert($.myAdd(options));//7};(function($){    $.extend({        myAdd:function(op){            if(typeof op === "undefined"){                var op = $.extend(defaults,op);//op中值替换defaults中的值并返回op            }            if(typeof op.x != "number"||typeof op.y !="number"){                return false;            }else{                return op.x+op.y;            }        }    });    var defaults ={        x:3,        y:9    }})(jQuery);



2.对象级别的拓展,即需要对象来调用

        ·拓展格式:

    $.fn.extend({          object//具体拓展    });

         ·$.fn是jquery的原型对象

我们知道 js 中用 prototype 来表示原型对象,如 Array.prototype 表示数组的原型对象,而 extend() 方法是用来为jquery原型添加新的属性和方法


0 0
原创粉丝点击