jQuery.extend()函数使用详解

定义:jQuery.extend()函数用于将一个或多个对象的内容合并到目标对象,是我们在编写插件过程中常用的方法,该方法有一些重载原型。

语法:$.extend(target , [object1] , [object2],… )它的含义是将object1,object2等合并到target中,返回值为合并的target

指示是否深度合并:$.extend( [deep] , target , [object1] , [object2],… )

上代码 ——

一:语法:$.extend(target , [object1] , [object2],... )

        var config1 = {
            name:"Bb",
            age: 20
        }
        var config2 = {
            name: "Yyf",
            sex: "boy"
        }
        var result = $.extend({},config1,config2);
        console.log(result);//{name: "Yyf", age: 20, sex: "boy"}
        console.log(config1);//{name: "Bb", age: 20}
        console.log(config2);//{name: "Yyf", sex: "boy"}

二:省略target参数:上述的target参数是可以省略的,则该方法就只能有一个object参数了,方法含义就变为:将该object合并到调用extend方法的对象中去,如:

            $.extend({
                hello:function(){
                    alert("helloWorld");
                }
            });
            $.hello();         //调用成功->helloWorld

.extend() .extend(boolean,target,object1,object2,…),含义–>第一个参数boolean代表是否深度拷贝,其余参数和前面的一致

        深度拷贝:
        //深度拷贝
        var info1 = {
            name: "Bb",
            location: {
                city: "nanchang",
                county: "china"
            }
        };
        var info2 = {
            last: "resign",
            location: {
                state: "MA",
                county: "USA"
            }
        };
        console.log($.extend(true,{},info1,info2))
    //{name: "Bb", location: {city:"nanchang",county:"USA",state:"MA"}, last: "resign"}
        console.log($.extend(false,{},info1,info2))
    //{name: "Bb", location: {county:"USA",state:"MA"}, last: "resign"}
        console.log($.extend({},info1,info2))
    //{name: "Bb", location: {county:"USA",state:"MA"}, last: "resign"}
//总结:深度拷贝可以将嵌套的子对象也进行合并。

你可能感兴趣的:(jquery)