JavaScript Deep clone objects

Source: Internet
Author: User
Tags hasownproperty

Today we see deep clones and require programming on the prototype Chain.
So the whim simply to review this knowledge point

Cloning objects , this noun looks tall, actually also nothing, is to copy a long identical object
Maybe it's not easy to have a beginner's little buddy.

var‘payen‘};var obj2 = obj1;

This is not a cloned object, obj1 and Obj2 are the same object at All.
They point to the same memory address space and get the same little House.
This is the value that should be referenced for the object
Speaking of reference values
Reference values in JavaScript are only objects
Notice here that the array is a special object, and the function is a special executable object.
In other words, they are also objects
The so-called deep cloning object is to say that it does not want the same house, the house you also want to copy me an identical
I don't know if you can understand = ̄ω ̄=.
That is, the reference value of the deep clone object is to be copied, and the relative shallow clone object just takes the reference Value.
Don't understand it doesn't matter, read the code to understand

Let's take a look at the shallow clone object First.

var  House = {name:  ' Payen ' , people: {father: true< /span>, mother: true }} function  easyclone   (obj)  { var  newObj = {}; for  (var  prop in  obj)        {if  (obj.hasownproperty (prop)) {newobj[prop] = obj[prop]; }} return  newObj;} var  newhouse = easyclone (house);  

Do not spit groove I use easy, for a moment I can not think of "shallow" English words (i do not know how I English level six how to Live)
About that For-in has a little performance problem, interested kids shoes can look at my another article
Portal O ( ̄▽ ̄) D
This piece of code is simple, and I don't have much to Explain.
Take a look at the chrome console

Looks like a great look.
So I'm doing one thing right now.
Add a person to a new house

It seems that this "new house" is not new ah, do not be confused by the name of the variable
so, with reference values appearing, shallow clones are not good.

So what do we do?
Now that we're going to get a new object, we'll create a new object, and then copy the contents of the old object to the new Object.
And one more question, what if there are objects in the object?
Then continue to repeat the process of creating the addition, which is obviously a looping process
But there are two types of loops

    • Iteration
    • Recursive

There's no question that recursion is better.
In a recursive loop, when a condition that satisfies a termination condition is encountered, the end is returned by layer
Then we can find the reference value recursively by layer until there is no reference Value.
Just look at the Code.

varHouse = {name:' Payen ', People: {father:true, Mother:true, Child: {age:1}}, Money: [ +, -, the]} function deepclone(original, target){    vartarget = Target | | {};//if target is undefined or not, set an empty object     for(varPropinchOriginal) {//traverse the original object        if(original.hasownproperty (prop)) {//copy only the inside of the object, regardless of the prototype chain            if(typeoforiginal[prop] = = =' object '){//reference Value                if(Object. prototype.toString.call (original[prop]) = = =' [object Array] ') {target[prop] = [];//handling Array Reference values}Else{target[prop] = {};//handling Object reference Values}//can be used with three mesh operatorDeepclone (original[prop],target[prop]);//recursive Cloning}Else{//base Valuetarget[prop] = original[prop]; }           }    }returntarget;}varNewhouse = Deepclone (house);

It says that If-else is suitable for the Three-mesh operator, but I feel too lengthy, obsessive-compulsive disorder.
To prove it was really deep-rooted, I made the original house Complicated.
(we do not consider deep clones of functions, which are troublesome and insignificant)
This time, it's really a new house.

I'm not going to Start.
You can see that the reference value of the new object changes, the old object does not change
Programming the same on the prototype chain

varHouse = {name:' Payen ', People: {father:true, Mother:true, Child: {age:1}}, Money: [ +, -, the]}Object. Prototype.cloneto = function(obj){    varobj = obj | | {}; for(varPropinch  this){if( this. hasownproperty (prop)) {if(typeof  this[prop] = = =' object '){if(Object. Prototype.toString.call ( this[prop]) ===' [object Array] ') {obj[prop] = []; }Else{obj[prop] = {}; } this[prop].cloneto (obj[prop]); }Else{obj[prop] = this[prop]; }        }    }returnobj;}varNewhouse = {};house.cloneto (newhouse);

= = = Home Portal = = =

JavaScript Deep clone objects

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.