首页 > 代码库 > Jquery extend() 方法

Jquery extend() 方法

Jquery 中$.extend() 方法用于实现合并多个对象的属性到第一个对象中。

$.extend(object1, [object2] );  

将后两个对象即object1和object2中的属性合并到object1中,默认是合并覆盖操作,不进行迭代。

此时object1 对object2 的拷贝为浅拷贝(公用一份实体,仅仅是引用变量不同)

<script type="text/javascript">  obj1 = {a: "this is a", b: "this is b"};  obj2 = {          a: {a_c: "this is a_c", a_d: "this is a_d"},          c: "this is c",           }  $.extend(obj1, obj2);  console.log(obj1.a);  // 输出 Object {a_c: "this is a_c", a_d: "this is a_d"}   // 覆盖了object1 中的a对象  console.log(obj1.a.a_c)         // 输出 this is a_c  obj2.a.a_c = "this is A_C";     // 改变obj2中a.a_c的值  console.log(obj1.a.a_c);        // 输出 this is A_C</script>

对于浅拷贝的简单实现

$ = {     extend : function(target, options) {        for (name in options) {            target[name] = options[name];        }        return target;    }};

 

若要进行合并迭代操作,则设置第一个参数为true,此时的拷贝为深拷贝(源对象与拷贝对象互相独立,其中任何一个对象的改动都不会对另外一个对象造成影响)

$.extend(true, object1, [object2] );

<script type="text/javascript">  obj1 = {a: {a_a: "this is a_a"}, b: "this is b"};  obj2 = {          a: {a_c: "this is a_c", a_d: "this is a_d"},          c: "this is c",           }  $.extend(true, obj1, obj2);  console.log(obj1.a);   // 输出 Object {a_a: "this is a_a", a_c: "this is a_c", a_d: "this is a_d"}   // 合并并迭代了object1中的a对象,不仅仅是覆盖  console.log(obj1.a.a_c);        // 输出 this is a_c  obj2.a.a_c = "this is A_C";     // 改变obj2中a.a_c值  console.log(obj1.a.a_c);        // 输出 this is a_C</script>

对于深拷贝的简单实现,需递归调用$.extend()实现迭代操作

$ = {    extend : function(deep, target, options) {        for (name in options) {            copy = options[name];            if (deep && copy instanceof Array) {                target[name] = $.extend(deep, [], copy);            } else if (deep && copy instanceof Object) {                target[name] = $.extend(deep, {}, copy);            } else {                target[name] = options[name];            }        }        return target;    }};

循环内有三种情况: 
1. 属性是数组时,target[name]初始化为空数组,递归调用extend; 
2. 属性是对象时,target[name]初始化为空对象,递归调用extend; 
3. 否则,直接复制属性。 

Jquery extend() 方法