Deep cloning of JavaScript objects _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces the deep cloning of JavaScript objects. This article describes in detail what object deep cloning is and provides sample code, if you need a friend, you can refer to it and do not know when to start. A new word appears in the front-end circle: Object deep cloning. It looks very big, but it is not new. In our actual project development, you may have used it for a long time, but because of the wide and profound Chinese characters, some simple things become mysterious after being slightly modified by seemingly professional words.

First, why do we need to perform deep cloning of an object? Let me make a guess: you sometimes think that the built-in object document of js is too long, so you may do this:

The Code is as follows:


Var d = document;
D. by = function (id ){
Return d. getElementById (id );
};
D. by ('id'). innerHTML = 'Hello sentsin ';

The above Code applies to document. getElementById is simplified, and a by member method is added to the original document object. You can use the document. hasOwnProperty ('by') returns the status value to verify your judgment. Let's look at the following example.

The Code is as follows:


Var person = {name: 'xianxin', Sion: 'frontend developer', place: 'hangzhou '};
Var newPerson = person;
NewPerson. age = '24 ';
Console. log (person );
// Result: {name: 'xianxin', projection: 'frontend developer', place: 'hangzhou', age: 24}

It can be seen that when an object is simply passed to a new variable, only an alias is added to the object. This means that through the operation on this alias, the original object key value will change. But the problem is that sometimes we want newPerson to be completely independent from person and there is no synchronization relationship between them, so we need to generate a copy. See the example below:

The Code is as follows:


Var cloneObj = function (obj ){
Var str, newobj = obj. constructor = Array? []: {};
If (typeof obj! = 'Object '){
Return;
} Else if (window. JSON ){
Str = JSON. stringify (obj), // serialized object
Newobj = JSON. parse (str); // restore
} Else {
For (var I in obj ){
Newobj [I] = typeof obj [I] === 'object '?
CloneObj (obj [I]): obj [I];
}
}
Return newobj;
};


// Test
Var obj = {a: 0, B: 1, c: 2 };
Var arr = [0, 1, 2];
// Execute deep cloning
Var newobj = cloneObj (obj );
Var newarr = cloneObj (arr );
// Delete a member of the new cloned object
Delete newobj.;
Newarr. splice (0, 1 );
Console. log (obj, arr, newobj, newarr );
// Result: {a: 0, B: 1, c: 2}, [0, 1, 2], {B: 1, c: 2}, [1, 2];

This is called object cloning. However, there are several points that need to be explained. The JSON objects and their member Methods stringify and parse in the Code belong to the ECMAScript5 specification. They are responsible for converting an object (including an array object) into a string, and restoring the object, so as to realize the deep copy of the object. For low-level browsers (such as IE), if you copy an array, you can use newobj. concat (obj). For normal objects, simply assign values to enumeration.

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.