The $.extend () method in Jquery is used to implement merging properties of multiple objects into the first object.
$.extend (Object1, [object2]);
Merges the properties from the latter two objects, Object1 and Object2, into Object1, which by default is a merge overwrite operation without iteration.
At this point object1 copy of the object2 is a shallow copy (a common entity, only the reference variable)
<script type= "Text/javascript" >obj1= {A: "This is a" and B: "This is B"}; Obj2={A: {a_c:"This is A_c", A_d: "The Is A_d"}, C:"This is C",} $.extend (Obj1, OBJ2); Console.log (obj1.a); //output Object {a_c: ' This is A_c ', A_d: ' This is A_d '} //overwrite a object in Object1Console.log (Obj1.a.a_c)//output This is A_cObj2.a.a_c = "This is A_c";//change the value of A.a_c in Obj2Console.log (Obj1.a.a_c);//output This is A_c</script>
Simple implementation for shallow copies
$ = { function(target, options) { for in options) { = options[name]; } return target; }};
To perform a merge iteration, set the first parameter to True, at which point the copy is a deep copy (the source and copy objects are independent of each other, and no changes to the other object are affected by any of the objects)
$.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: "The Is A_d"}, C:"This is C",} $.extend (true, Obj1, obj2); Console.log (obj1.a); //output Object {a_a: ' This is A_a ', A_c: ' This is A_c ', A_d: ' This is A_d '} //merges and iterates over the A object in Object1, not just the overlayConsole.log (Obj1.a.a_c); //output This is A_cObj2.a.a_c = "This is A_c";//change a.a_c value in Obj2Console.log (Obj1.a.a_c);//output This is A_c</script>
For a simple implementation of a deep copy, recursive invocation of $.extend () is required to implement the iterative operation
$ ={Extend:function(deep, target, options) { for(Nameinchoptions) {Copy=Options[name]; if(Deep && CopyinstanceofArray) {Target[name]=$.extend (deep, [], copy); } Else if(Deep && CopyinstanceofObject) {Target[name]=$.extend (Deep, {}, copy); } Else{Target[name]=Options[name]; } } returnTarget; }};
There are three kinds of situations in the loop:
1. When the property is an array, target[name] initializes to an empty array, recursively calls extend;
2. When the property is an object, Target[name] initializes to an empty object and calls extend recursively;
3. Otherwise, copy the properties directly.
Jquery Extend () method