jQuery.extend()、jQuery.fn.extend()擴(kuò)展方法示例詳解

字號:


    jQuery自定義了jQuery.extend()和jQuery.fn.extend()方法.其中jQuery.extend()方法能夠創(chuàng)建全局函數(shù)或者選擇器,而jQuery.fn.extend()方法能夠創(chuàng)建jQuery對象方法.
    例如:
    代碼如下:
    jQuery.extend({
    showName : function(name){
    alert(name)
    }
    });
    jQuery.showName("深藍(lán)");
    jQuery.extend()除了可以創(chuàng)建插件外,還可以用來擴(kuò)展jQuery對象.
    例如:
    代碼如下:
    var a = {
    name : "blue",
    pass : 123
    }
    var b = {
    name : "red",
    pass : 456,
    age : 1
    }
    var c = jQuery.extend({},a,b);
    c擁有a,b對象的屬性,由于,b對象在a對象之后,其name屬性優(yōu)先在c對象里.
    jQuery.extend()方法為插件傳遞系列選項(xiàng),包括默認(rèn)值.
    代碼如下:
    function fn(options){
    var options = jQuery.extend({ //默認(rèn)參數(shù)選項(xiàng)列表
    name1 : value1,
    name2 : value2,
    name3 : value3
    },options); //使用函數(shù)的參數(shù)覆蓋或合并到默認(rèn)參數(shù)選項(xiàng)列表中
    //函數(shù)體
    }
    fn({ name1 : value3, name2 : value2 , name3 : value1 });//使用新值
    fn({ name4 : value3, name5 : value2 });//在默認(rèn)上添加新選項(xiàng)
    fn(); //保持默認(rèn)選項(xiàng)值
    當(dāng)在調(diào)用該方法時,傳遞新的參數(shù)值,就會覆蓋掉默認(rèn)的參數(shù)選項(xiàng)值,否則,使用默認(rèn)參數(shù)值.
    使用JQuery.fn對象創(chuàng)建JQuery對象方法
    可以通過jQuery.fn對象來添加屬性和方法,實(shí)際上jQuery.fn對象就是掛接在jQuery.prototype上的,jQuery把它簡寫了.
    fn 是什么東西呢。查看jQuery代碼,就不難發(fā)現(xiàn)。
    代碼如下:
    jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {//.... 
    //......
    };
    原來 jQuery.fn = jQuery.prototype.對prototype肯定不會陌生啦。
    例如:
    代碼如下:
    jQuery.fn.test = function(){
    alert("這是jQuery對象方法!");
    }
    jQuery("div").click(function(){
    $(this).test(); //在當(dāng)前的jQuery對象上調(diào)用test()方法
    });
    我們可以調(diào)用jQuery.fn.extend()方法來創(chuàng)建jQuery對象方法.
    代碼如下:
    jQuery.fn.extend({
    test : function(){
    return this.each(function(){
    alert(this.nodeName)
    });
    }
    });
    jQuery("body *").click(function(){
    $(this).test(); //調(diào)用jQuery對象方法
    });
    一句話:jQuery.extend是對JQuery類的自定義擴(kuò)展,jQuery.fn.extend是對JQuery對象的自定義擴(kuò)展.