JavaScript basic knowledge of shallow copy and deep copy

Source: Internet
Author: User
Tags arrays extend instance method shallow copy

The following small series brings us a brief discussion of object-oriented deep copy and shallow copy in JavaScript. Small make up feel very good, now share to everyone, also give you a reference.

1. Shallow copy: Copy a reference, all reference objects point to a piece of data, and can modify this data.

2. Deep copy (complex): Copy the value of the variable, for a variable of a non basic type, then recursively to the base type variable, then copy.

Here, draw a simple diagram to deepen your understanding:

One, the depth of the copy of the array

When working with JavaScript arrays, we often need to back up the array, and it turns out that if we simply give it to other variables, we just change any one of them, and then the others will change, which causes the problem to occur.

var arr = ["One", "two", "Three"];
var arrto = arr;
ARRTO[1] = "Test";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,test,three Document.writeln
("New value for array:" + Arrto + "<br/>");//export: New value for array: One,test,three

Such direct assignment as above is a shallow copy, many times, this is not the result we want to get, in fact, we want the value of arr is unchanged, is not it?

Method One: JS's slice function

var arr = ["One", "two", "Three"];
var Arrtoo = arr.slice (0);
ARRTOO[1] = "Set Map";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,two,three Document.writeln
("New value for array:" + Arrtoo + "<br/>");//export: New value for array: One,set Map,three

Method Two: Concat method of JS

var arr = ["One", "two", "Three"];
var arrtooo = Arr.concat ();
ARRTOOO[1] = "Set Map to";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,two,three Document.writeln
("New value for array:" + Arrtooo + "<br/>");//export: New value for array: One,set MAP to,three

Second, the depth of the copy of the object

var a={name: ' yy ', age:26};
var b=new Object ();
B.name=a.name;
B.age=a.age;
A.name= ' xx ';
Console.log (b);//object {name= "yy", age=26}
Console.log (a);//object {name= "xx", age=26}

is to iterate over the attributes of an object and assign it to a new object.

var deepcopy= function (source) { 
var result={};
for (var key in source) {
 Result[key] = typeof source[key]=== ' object '? Deepcoyp (Source[key]): Source[key];
 } 
 return result; 
}

Take an example of jquery:

Jquery.extend = JQuery.fn.extend = function () {//1. Extends the Extend method to the bottom of the JQ (function): extends the static method//2. JQuery.fn.extend extends extend to Jq.fn and Jquery.fn = Jquery.prototype Extended instance method//1.2. feature similar var options, name, SRC, copy, Copyisarray, clone,//define some variables target = arg Uments[0] | |
 {},//target element is "0" first element $.extend (A, {name: ' Hello '}, {age:30}); i = 1,//The position length of the first element = arguments.length,//the element deep = False of the first object; is a deep copy default false is not//Handle a deep copy situation see whether the deep copy situation if (typeof target = = "Boolean") {//is a Boolean value deep = Targ
 Et target = Arguments[1] | | {};
 The destination element is the second $.extend (true, A, b)//Skip the Boolean and the target i = 2; //Handle case when the target is a string or something (possible in deep copy) to see if the parameter is correct (typeof target!== "Object" &A mp;&!jquery.isfunction (target) {///when the target is not an object or not a function target = {};//Becomes an empty Jason}//Extend jQuery itself if O Nly One argument is passed see if plug-in condition if (length = = i) {//Only write an object to extend this object to the JQ source code static method or instance method target = this;//thisis $ or $ ();
 I.; //There may be multiple object cases for (; i < length; i++) {//only deal with non-null/undefined values if (options = arguments[I
 ]!= null) {//See whether the object behind has a value//Extend the Base object for (name in options) {src = target[name];

 copy = options[name]; Prevent never-ending loop if (target = = copy) {//Prevent circular reference continue;//from jumping out of this loop continue//$.extend (A, {name:a}) Circular reference A is also an object}//Recurse If we ' re merging plain objects or arrays deep copy if (Deep && copy && (jQuery). Isplainobject (copy) | | (Copyisarray = Jquery.isarray (copy)) {//is a deep copy and needs to have var B = {name: {age:30}}; and b must be an object argument (Jason) or array//recursive if (Copyisarray) {//Arrays Copyisa
  Rray = false; clone = src && jquery.isarray (src)? SRC: [];
  Define an empty array} else {//jason clone = src && jquery.isplainobject (src)? src: {};//Look at the original properties there is no and Jason defines an empty Jason }//var a = {name: {job: ' It '}};
  See if there are any original attributes. Add//var B = {name: {age:30}}; //$.extend (True, A, b);//a inheritance b//Console.log (a); a{name:{job: ' It ', age:30}} if only one {} only, age:30//Never Move original objects, Clone (a) them target[name] = 
  Jquery.extend (deep, clone, copy); Call the function itself for further recursion//Don ' t bring in undefined values shallow copy} else if (copy!== undefined) {target[name] = copy;
/Direct copy because there is no object in the inside}}//Return the modified object return target;
 };

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.