$.extend的作用

第一次看见这个用法是在一个jquery的插件开发中看见的写法,用来对默认参数和自定义参数的覆盖。
一般的使用场景:

function XXX(opt){
var def = {}//默认配置
var optRea = $.extend({},def,opt)
}

在这样的覆盖中,如果opt的属性有和def默认的配置有一个的key的话,就会去直接覆盖掉相应的属性,而不会去影响到其他的属性。
今天在开发工作中又看到了$.extend()新的用法,就是在搜索中的使用。
在搜索栏中输入相应的名称,界面就只显示对应的信息。
运用$.extend的方法也是大相径庭的。

$.extend(this.sData, {name: this.soso});//其实之前还会this.sData ={},所以 并没有觉得这儿有多大的作用
$.extend(param, this.sData);//param是默认的参数 里面会获取到本身所有的数据 然后再和sData做覆盖
这样就做到了只要name 等于this.soso

除了这样的用法,还可以进行深度遍历,保留其下的对象或者数组的其他值,只覆盖对应的属性。

$(document).ready(function() {
    var htmlCode, statusCh, node;
    var object1 = {
        apple: [0,1,2,34],
        banana: {
            weight: 52,
            price: 100
        },
        cherry: 97
    };
    var object2 = {
        banana: {
            price: 200
        },
        durian: 100
    };
    var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
        var arr = [];
        $.each(obj, function(key, val) {
            var next = key + ": ";
            next += $.isPlainObject(val) ? printObj(val) : val;
            arr.push(next);
        });
        return "{ " + arr.join(", ") + " }";
    };
    console.log(printObj(object1))
    $.extend(object1,{banana: {
            weight: 55,
        }})
    console.log(printObj(object1))
})
[Log] {"apple":[0,1,2,34],"banana":{"weight":52,"price":100},"cherry":97} (line 28)
[Log] {"apple":[0,1,2,34],"banana":{"weight":55},"cherry":97} (line 32)

这个时候我们会发现,banana的其他属性被覆盖了,就是没有进行深度遍历。
只需要在第一个参数改成true就可以了。

    console.log(printObj(object1))
    $.extend(true,{banana: {
            weight: 55,
        }})
    console.log(printObj(object1))
[Log] {"apple":[0,1,2,34],"banana":{"weight":52,"price":100},"cherry":97} (base.js, line 28)
[Log] {"apple":[0,1,2,34],"banana":{"weight":52,"price":100},"cherry":97} (base.js, line 32)

下面是jquery实现的代码

jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
                //target是要被拷贝的目标函数
        target = arguments[ 0 ] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // Skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
        target = {};
    }


       //针对jQuery的extend原型的功能
    // Extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }
        //遍历要被复制的对象
    for ( ; i < length; i++ ) { 

        // Only deal with non-null/undefined values
        if ( ( options = arguments[ i ] ) != null ) {

            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
                    ( copyIsArray = jQuery.isArray( copy ) ) ) ) {

                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray( src ) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject( src ) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

你可能感兴趣的:($.extend的作用)