JS object light Copy and deep copy detailed _javascript skills

Source: Internet
Author: User
Tags shallow copy

This article for everybody to share the JavaScript object's shallow copy and the deep copy code, for everybody reference, the concrete content is as follows

1. Shallow copy

A copy is a copy of the parent's image attribute, all copied to the child object.

The following function is making a copy:

var Chinese = {
Nation: ' China '
}
var doctor = {
career: ' Doctor '
}
function Extendcopy (p) {
var c = {};
for (var i in P) { 
c[i] = p[i];
}
c.uber = p;
return C;
}

When used, write like this:

var doctor = extendcopy (Chinese);
Doctor.career = ' Doctor ';
alert (doctor.nation); China

However, there is a problem with such a copy. That is, if the parent object's properties are equal to an array or another object, the child object actually gets only a memory address, not a real copy, so there is a possibility that the parent object has been tampered with.

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

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

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

var doctor = extendcopy (Chinese);

Then, we add a city for doctor's "birthplace":

Doctor.birthPlaces.push (' Xiamen ');

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 births have been changed.

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

2. Deep copy

Because the handcuffs are so flawed, so let's take a look at the deep copy.

The so-called "deep copy" is the ability to achieve the true meaning of the array and the copy of the object. Its implementation is not difficult, as long as the recursive call "shallow copy" on the line.

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 a property to the parent object, and the value is an array. Then, modify the property on the child object:

chinese.birthplaces = [' Beijing ', ' Shanghai ', ' Hong Kong '];
Doctor.birthPlaces.push (' Xiamen ');

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

This completes the copy;

$.extend ()

In jquery $.extend () is like.

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

deep
Type: Boolean
If true, the merge becomes recursive (also called a deep copy).
Target
Type: Object
Object extensions. This will receive the new property.
Object1
Type: Object
An object that contains additional attributes to merge into the first argument.
objectn
Type: Object
Contains additional attributes to merge to 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 argument 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 functionality 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 via $.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 itself is an object or an array, it overrides a property entirely with the same key as the second object. These values are not merged. You can understand this by examining the value of banana in the example below. However, if true is the first parameter of the function, a recursive merge is performed on the object.

Warning: The first parameter pass false is not supported.

1. Merges two objects and modifies the first object.

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<8
Console.log (json.stringify (Object1));
{"Apple": 0, "banana": {"Price": $}, "Cherry": "", "Durian": 100}

2. Recursively merges two objects and modifies the first object.

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<8
Console.log (json.stringify (Object1));
{"Apple": 0, "banana": {"Weight": "", "Price": "," Cherry ":", "Durian": 100}

3. Merge defaults and Options objects without modifying the Defaults object. This is a common plug-in development model.

var defaults = {Validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};

Merge defaults and options, without modifying defaults
var settings = $.extend ({}, defaults, options);


Console.log (json.stringify (defaults));
Console.log (Options) (json.stringify);
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, equality operations include "= =", "= =" congruent, the difference between the two, do not have a majority, this article we will tell in the future how to determine whether two objects are equal? You might think that if two objects have the same attributes, and their properties have the same value, then the two objects are equal. So here's an example to illustrate:

var obj1 = {
  name: "Benjamin",
  Sex: "Male"
}

var obj2 = {
  name: "Benjamin",
  Sex: "Male"
}
   //outputs:false
console.log (obj1 = = obj2);

Outputs:false
console.log (obj1 = = obj2);

You can see from the example above that you return false regardless of whether you use "= =" or "= =". The main reason is that the base type String,number is compared by value, while objects (Date,array) and ordinary objects are compared through the addresses in the memory that the pointer points to. Look at one of the following examples:

var obj1 = {
  name: "Benjamin",
  Sex: "Male"
};

var obj2 = {
  name: "Benjamin",
  Sex: "Male"
};

var obj3 = obj1;

Outputs:true
console.log (obj1 = = obj3);

Outputs:true
console.log (obj1 = = obj3);

Outputs:false
console.log (obj2 = = obj3);

Outputs:false
console.log (obj2 = = obj3);

The previous example returns True because the Obj1 and ob3 pointers 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 the corresponding values of the attributes are the same, or what?

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 entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.