Deeper understanding of deep copy and shallow copy of JavaScript

Source: Internet
Author: User

JavaScript has five basic data types (that is, simple data types), namely: Undefined,null,boolean,number and String. Also contains a complex data type, which is the object

Note the difference between undefined and null, the undefined type has only one value, that is, the Undefined,null type has only one value, which is null
Undefined is actually the result of declaring a variable output that has not been assigned
Null is actually the result of a nonexistent object

var c;console.log(c)//undefinedconsole.log(document.getElementById(‘wsscat‘))//没有id为wsscat的节点,输出null

Simple data types and complex data types have the following important differences

For simple data types

Their values occupy a fixed amount of space in memory and are stored in the stack memory. When a variable copies the value of a base type to another variable, a copy of the value is created, and there is no attribute added to the value of the base data type

var a = 1;var b = a;a.attr = ‘wsscat‘;console.log(a.attr)//undefined

In the code above, A is a simple data type (number) and B is a copy of a, both of which occupy different positions but equal memory space

For complex data types

A complex data type is a reference type whose value is an object, stored in heap memory, and a variable containing a reference type value actually contains not the object itself, but a pointer to that object. Copying the value of a reference type from one variable to another is actually a pointer, so two variables end up pointing to the same object.

var obj = {            name:‘wsscat‘,            age:0        }        var obj2 = obj;        obj2[‘c‘] = 5;        console.log(obj);//Object {name: "wsscat", age: 0, c: 5}        console.log(obj2);////Object {name: "wsscat", age: 0, c: 5}

We can see that when obj is assigned to OBJ2, when we change the property value of one of the objects, two objects are changed, and the reason for the situation is that because both the obj and OBJ2 variables point to the same pointer, the assignment simply copies the pointer, so when we change one of the values it affects the value of the other variable.

Shallow copy

In fact, this code is a shallow copy, sometimes we just want to back up the array, but simply let it be assigned to a variable, change one of them, the other one will follow the change, but many times this is not what we want

var obj = {            name:‘wsscat‘,            age:0        }        var obj2 = obj;        obj2[‘c‘] = 5;        console.log(obj);//Object {name: "wsscat", age: 0, c: 5}        console.log(obj2);////Object {name: "wsscat", age: 0, c: 5}
Deep copy

Array
For arrays we can use slice() and concat() methods to solve the above problems
Slice

var arr = [‘wsscat‘, ‘autumns‘, ‘winds‘];        var arrCopy = arr.slice(0);        arrCopy[0] = ‘tacssw‘        console.log(arr)//[‘wsscat‘, ‘autumns‘, ‘winds‘]        console.log(arrCopy)//[‘tacssw‘, ‘autumns‘, ‘winds‘]

Concat

var arr = [‘wsscat‘, ‘autumns‘, ‘winds‘];        var arrCopy = arr.concat();        arrCopy[0] = ‘tacssw‘        console.log(arr)//[‘wsscat‘, ‘autumns‘, ‘winds‘]        console.log(arrCopy)//[‘tacssw‘, ‘autumns‘, ‘winds‘]

Object
Object we can define a new object and traverse the new property to implement a deep copy

var obj = {            name:‘wsscat‘,            age:0        }        var obj2 = new Object();        obj2.name = obj.name;        obj2.age = obj.age        obj.name = ‘autumns‘;        console.log(obj);//Object {name: "autumns", age: 0}        console.log(obj2);//Object {name: "wsscat", age: 0}

Of course we can encapsulate the good one method to handle the deep copy of the object, the code is as follows

var obj = {
Name: ' Wsscat ',
age:0
}
var deepcopy = function (source) {
var result = {};
for (var key in source) {
if (typeof source[key] = = = ' object ') {
Result[key] = deepcopy (Source[key])
} else {
Result[key] = Source[key]
}
}
return result;
}
var obj3 = deepcopy (obj)
Obj.name = ' autumns ';
Console.log (obj);//object {name: "Autumns", age:0}
Console.log (OBJ3);//object {name: "Wsscat", age:0}

In JavaScript, a function is also a type of data that can manipulate an object as if it were manipulated. And JavaScript does not do data type checking, the array can hold anything, in the following code we not only in the array to store the function, and can also hold a return value of the execution function, so the first two of the array of data storage is function execution return value

var funcA = function() {            console.log("funcA");            return "hello funA";        }        var funcB = function() {            console.log("funcB");            return "hello funB";        }        var funcC = function() {            console.log("funcC");            return "hello funC";        }        var arr = [funcA(), funcB(), funcC];        console.log(arr);        arr[2]();
The result of the output is as follows

Deeper understanding of deep copy and shallow copy of JavaScript

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.