jQuery插件开发(一):jQuery类方法

一、jQuery插件开发的方法

  jQuery插件的编写方法主要有两种:

  1、基于jQuery对象的插件

  2、基于jQuery类的插件

二、基于jQuery类的插件

  1、什么是jQuery类的插件?

    jQuery类方法其实就是jquery全局函数,即jquery对象的方法,实际上就是位于jquery命名空间的内部函数。这些函数有一个特征就是不操作DOM元素,而是操作  Javascript非元素对象。直观的理解就是给jquery类添加类方法,可以理解为添加静态方法

  2、给jQuery类添加方法。

    //添加两个全局函数
    jQuery.foo = function(){
        console.log("this is foo");
    };
    jQuery.foo();//this is foo

    jQuery.bar = function(){
        console.log("this is bar")
    };
    jQuery.bar();// this is bar

  3、使用jQuery.extend()函数

    jQuery自定义了jQuery.extend()与jQuery.fn.extend()方法,jQuery.extend()能够创建工具函数或者选择器,jQuery.fn.extend()能够创建jQuery对象命令。

    //使用jQuery.extend()函数
  jQuery.extend({ foo:
function(){ console.log("this is foo"); }, bar:function(){ console.log("this is bar") }, }); $.foo();//this is foo $.bar();// this is bar

  4、使用命名空间

     虽然在jQuery命名空间中,禁止使用大量的Javascript函数名和变量名,但是仍然不可避免某些函数名或变量名与其他jQuery插件冲突,因此习惯将一些方法封装到另一个自定义的命名空间。   

    //使用命名空间

    jQuery.myPlugin = {
        foo:function(){
            console.log('this is foo');
        },
        bar:function(){
            console.log('this is bar');
        },
    };

    $.myPlugin.foo();
    $.myPlugin.bar();