Shallow copy and deep copy of JS object

Source: Internet
Author: User

Shallow copy and deep copy of JS object

i10630226 font: [Increase decrease] Type: Reprint time: 2016-09-05 I want to comment

This article mainly for you in detail the JavaScript object of the shallow copy and deep copy code, with a certain reference value, interested in small partners can refer to

This article for everyone to share the JavaScript object of the shallow copy and deep copy code for your reference, the specific content is as follows

1. Shallow copy

A copy is a copy of the parent-to-image property, all of which are copied to the child object.

The following function is making a copy:

?
1234567891011121314 var Chinese = {  nation:‘中国‘}var Doctor = {  career:‘医生‘}  function extendCopy(p) {    var c = {};    for (var i in p) {       c[i] = p[i];    }    c.uber = p;    return c; }

When used, write this:

?
123 varDoctor = extendCopy(Chinese);Doctor.career = ‘医生‘;alert(Doctor.nation); // 中国

However, there is a problem with such a copy. That is, if the parent object's property is equal to an array or another object, then actually the child object obtains only one memory address, not a real copy, so there is a possibility that the parent object will be tampered with.

See, now add a "birthplace" property to Chinese, whose value is an array.

chinese.birthplaces = [' Beijing ', ' Shanghai ', ' Hong Kong '];

With the Extendcopy () function, doctor inherits the Chinese.

var Doctor = extendcopy (Chinese);

We then add a city to the birthplace of doctor:

Doctor.birthPlaces.push (' Xiamen ');

Take a look at the input results

alert (doctor.birthplaces); BEIJING, Shanghai, Hong Kong, Xiamen
alert (chinese.birthplaces); BEIJING, Shanghai, Hong Kong, Xiamen

As a result, two of the birth land were changed.

So, extendcopy () just copies the basic types of data, and we call this copy "shallow copy."

2. Deep copy

Because it's so bad, we'll take a look at the deep copy.

The so-called "deep copy" is the ability to make real-world copies of arrays and objects. Its implementation is not difficult, as long as the recursive call "shallow copy" on the line.

?
123456789101112 function deepCopy(p, c) {    var c = c || {};    for (var i in p) {      if (typeof p[i] === ‘object‘) {        c[i] = (p[i].constructor === Array) ? [] : {};        deepCopy(p[i], c[i]);      } else {         c[i] = p[i];      }    }    return c;  }

Take a look at how to use:

var Doctor = deepcopy (Chinese);

Now, add an attribute to the parent object, and the value is an array. Then, modify this property on the child object:

?
12345 Chinese.birthPlaces = [‘北京‘,‘上海‘,‘香港‘];Doctor.birthPlaces.push(‘厦门‘);alert(Doctor.birthPlaces); //北京, 上海, 香港, 厦门alert(Chinese.birthPlaces); //北京, 上海, 香港

This completes the copy;

$.extend ()

$.extend () in jquery is like.

$.extend ([deep], Target, Object1 [, Objectn])

? deep
Type: Boolean
If true, the merge becomes recursive (also known as a deep copy).
? target
Type: Object
Object extension. This will receive the new attribute.
? object1
Type: Object
An object that contains additional attributes to merge into the first parameter.
? objectn
Type: Object
Incorporate additional attributes into the first parameter

When we provide two or more objects to $.extend (), all properties of the object are added to the target object (target parameter).

If only one parameter is supplied to $.extend (), this means that the target parameter is omitted. In this case, the jquery object itself is default to the target object. In this way, we can add new features under the jquery namespace. This is useful for plug-in developers wishing to add new functions to jQuery.

Keep in mind that the target object (the first parameter) will be modified and will be returned by $.extend (). However, if we want to preserve the original object, we can pass an empty object as the target object:

var object = $.extend ({}, Object1, object2);

By default, the $.extend () merge operation is not recursive, and if the property of the first object is itself an object or an array, it overrides a property entirely with the same key as the second object. These values are not merged. This can be understood by examining the value of banana in the example below. However, if true is the first parameter of the function, then a recursive merge is performed on the object.

Warning: The first parameter passed false is not supported.

1. Merge two objects and modify the first object.

?
12345678910111213141516 var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97};var object2 = { banana: { price: 200 }, durian: 100}; // Merge object2 into object1$.extend( object1, object2 );// Assuming JSON.stringify - not available in IE<8console.log( JSON.stringify( object1 ) );//{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}

2. Merge two objects recursively and modify the first object.

?
12345678910111213141516 var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97};var object2 = { banana: { price: 200 }, durian: 100};// Merge object2 into object1, recursively$.extend( true, object1, object2 );// Assuming JSON.stringify - not available in IE<8console.log( JSON.stringify( object1 ) );//{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}

3. Merge the defaults and Options objects, and do not modify the defaults object. This is a common plug-in development model.

?
12345678910111213 var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" }; // Merge defaults and options, without modifying defaultsvar settings = $.extend( {}, defaults, options );console.log(JSON.stringify( defaults ));console.log(JSON.stringify( options ));console.log(JSON.stringify( settings ));//defaults -- {"validate":false,"limit":5,"name":"foo"}//options -- {"validate":true,"name":"bar"}//settings -- {"validate":true,"limit":5,"name":"bar"}

Javascript determines whether objects are equal

In JavaScript The equality operation includes "= =", "= = =" Congruent, the difference between the two, do not need the majority, this article we will tell how to determine whether two objects are equal? You might think that if two objects have the same properties and their properties have the same value, then the two objects are equal. So here's an example to illustrate the following:

?
123456789101112131415 var obj1 = { &NBSP;&NBSP; name: "Benjamin" &NBSP;&NBSP; sex: "male" }  var obj2 = { Code class= "JS spaces" >&NBSP;&NBSP; name: "Benjamin" &NBSP;&NBSP; sex: "male" }  // Outputs:false console.log (obj1 = = obj2);  //outputs:false console.log (obj1 = = = Obj2);

As you can see from the example above, return false regardless of whether you use "= =" or "= = =". The main reason is that the base type String,number is compared by the value, while the object (Date,array) and the normal object are compared by the address in memory pointed to by the pointer. Take a look at the following example:

?
1234567891011121314151617181920212223 var obj1 = {  name: "Benjamin",  sex : "male"};var obj2 = {  name: "Benjamin",  sex : "male"};var obj3 = obj1;//Outputs: trueconsole.log(obj1 == obj3);//Outputs: trueconsole.log(obj1 === obj3);//Outputs: falseconsole.log(obj2 == obj3);//Outputs: falseconsole.log(obj2 === obj3);

The above example returns true because the pointers to Obj1 and Ob3 point to the same address in memory. is similar to the concept of value passing and reference passing in object-oriented language (java/c++). Because, if you want to determine whether two objects are equal, you have to be clear, do you want to determine whether the properties of the two objects are the same, or whether the properties correspond to the same values, or what?

?
123456789101112131415 function person(name) {   this.name=name; } var p1 = new person("p1"); var p2 = new person("p2"); console.log(p1 == p2); //false person.prototype.sayHi = function() {   // do sayHi here } console.log(p1.sayHi() == p2.sayHi()); //true console.log(p1.sayHi() === p2.sayHi()); //true

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support the script home.

Shallow copy and deep copy of JS object

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.