The $.extend () method of the deep copy and light copy from JS to JQ

Source: Internet
Author: User
Tags shallow copy

One, heap memory and stack memory

Both the heap and the stack are divided in memory to store the area, the stack is automatically allocated memory space, it is automatically released by the system, the heap is dynamically allocated memory, the size is not automatically released.

Second, JS basic data types and reference types are different

Basic data type (boolean,undefined,null,string,number)

1. Basic data types are stored in stack memory

is a simple data segment stored in the stack, the data size is determined, the size of the memory space can be allocated, directly by the value of the storage, so you can directly access.

2. Basic data type value is not variable

JS in the basic type assignment or operation of the basic type of data, does not change the primitive type of the original value, the number and the value of the Boolean type is obviously immutable, the string although there are many ways to operate, but all are in the creation of a new string, its original value has not changed.

3. Comparison of basic data types is a comparison of values

As long as their values are equal, they are considered equal.

var a = 1; var b = 1= = b); // true

It is best to use strict and so on, otherwise it will be type conversion;

var a = 0; var b = ' 0 '= = b); // true // false

Reference types (Arrays, objects, functions)

1. Reference types are stored in heap memory

2. Variable reference type value

3. Comparison of reference types is a reference comparison

var a = [n/a]; var b = [All-in-a-c = =]; // false

Compares a reference to two objects to see if two references point to the same object

Basic data types and reference type assignment comparisons

The basic data type assignment is the passing of the value, first opening a memory in the stack memory, and then assigning the value to the new stack

var a = ten; var b =++/  /One//  

The assignment of a reference type is the assignment of the address of the variable that is stored in the stack, so that the two variables point to the same object, so that the two variables affect each other;

var a = {}; var b == "qy"; Console.log (a.name); // qyConsole.log (b.name); // qyb.age =console.log (a.age); // Console.log (b.age); // 22
Console.log (A = = B);//true

Assignment is not a shallow copy, the difference between an assignment and a shallow copy

varObj1 ={// raw data "Name": "Zhangsan",  "Age": "22",  "Language": [1, [2, 3], [4, 5]] }varObj2 =obj1;// worthy of the varObj3 =shallowcopy (OBJ1);// shallow copy gets functionshallowcopy (src) {varDST = {};  for(varPropinchsrc) {       if(Src.hasownproperty (prop)) {Dst[prop]=Src[prop]; }   }   returnDST;} Obj2.name= "Lisi"; //Change the base type property of the obj2 that is worthy of the name, and the final result is that the attributes in the original data change as well obj3.age= "11"; //Change the basic type attribute of the OBJ3 obtained by the light copy to age, the result is that the age property of the original data has not changed obj2.language[1] = [' A ', ' B ']; //Change the property of the reference type of the OBJ2, the result is that the original data and the language properties of the obj3 obtained from the shallow copy of the original data are changed obj3.language[2] = [' C ', ' d ']; //Change the reference type attribute of the obj3 obtained by the shallow copy, the result is that the original data and the Obj2 language attribute with the original data are changed Console.log (OBJ1);//Name:lisi,age:22,language:[1,[a,b],[c,d]]Console.log (OBJ2);//Name:lisi,age:22,language:[1,[a,b],[c,d]]Console.log (OBJ3);//Name:zhangsan,age:11,language:[1,[a,b],[c,d]]

Conclusion: (First, it is necessary to clarify that both deep and shallow copies are for reference types, the basic data types are not related to deep copy and shallow copy)

The assignment of the @1 reference type is the delivery of the address, that is, the new data is assigned to the same object in the heap memory as the original data, and the two still affect each other;

@2 a shallow copy is by creating a new object (array, object), and then copying each property of the object, at this point, if the object's property is a reference type, then the copied reference type property is still pointing to the same object as the reference type property address of the original data, so the new data obtained by a shallow copy, The attribute of the reference type to the original data will affect each other;

@3 so deep copy is what, deep copy is to do the new data and the original data completely non-impact (whether the basic type or reference type);

Third, how to make a deep copy?

Idea: Recursive call shallow copy method, copy each level of object property; The following is the Extend method of Zepto

$.extend =function(target) {varDeep , args= Slice.call (arguments, 1); if(typeoftarget = = ' Boolean ') { deep=Target; //Target takes a second argumenttarget =Args.shift (); }            //iterate over the parameters, all merged into TargetArgs.foreach (function(ARG) {Extend (target, ARG, deep)})returnTarget; }        functionExtend (target, source, deep) { for(Keyinchsource) {                //is a deep copy and is an array or object                if(Deep && (Isplainobject (source[key)) | |IsArray (Source[key])) {                    //Source[key] is an object, and Target[key] is not an object, then Target[key] initializes it, or the recursive error                    if(Isplainobject (Source[key]) &&Isplainobject (Target[key])) {Target[key]= {}; }                    //Source[key] is an array, and Target[key] is not an array and is initialized                    if(IsArray (Source[key]) &&!IsArray (Target[key])) {Target[key]= []; }                    //perform recursionextend (Target[key], Source[key], deep); } Else if(Target[key]!==undefined) {Target[key]=Source[key]; }            }        }

Iv. $.extend () method (extend extension method for jquery)

1, Prototype: Extend (DEST,SRC1,SRC2,SRC3 ...);

Meaning: Will src1,src2,src3 ... Merge into dest, return value is merged dest

2, dest can be {}

var newsrc=$.extend ({},src1,src2,src3 ...) That is, "{}" as the Dest parameter.

Meaning: This can be src1,src2,src3 ... Merge, and then return the merge results to NEWSRC;

Cases:

var result=$.extend ({},{name: "Tom", Age:21},{name: "Jerry", Sex: "Boy"})// The result is: Result={name: "Jerry", Age:21,sex: "Boy"}

It is visible that the parameters later in this method will overwrite the previous parameter values if they have the same name as the previous parameter.

3. Overload prototype 1: Omit the dest parameter, then the method can have only one src parameter, and it is to merge the src into the object calling the Extend method.

Cases:

$.extend ({hello:function() {alert (' hello ');}}); // Merge The Hello method into the global object of jquery

4, heavy-duty prototype 2extend (BOOLEAN,DEST,SRC1,SRC2,SRC3 ...)

Meaning: The first parameter, Boolean, indicates whether to make a deep copy, other parameters as above;

var result = $.extend (true, {}, {name: "A", Location:{city: "Beijing", pos:1000}}, {age:12, location:{city: "Hanguo", Age:20}})result={name: "A", Age:12, Location: {City: "Hanguo", pos:1000, Age:20}};

var result = $.extend (false, {}, {name: "A", Location:{city: "Beijing", pos:1000}}, {age:12, location:{city: "H Anguo ", age:20}});

result= {name: "A", Age:12, Location: {City: "Hanguo", Age:20}}}

The $.extend () method of the deep copy and light copy from JS to JQ

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.