In-depth introduction to javascript Object cloning _ basic knowledge

Source: Internet
Author: User
This article will introduce in detail the classification and implementation of js deep cloning. If you need it, you can refer to the following two types of js values:
Basic type (including undefined, Null, boolean, String, Number), passed by value;
The reference type (including arrays and objects) is passed by address. The reference type is the address in the memory when the value is passed.
There are two types of clone or copy:
Simple clone: the basic type is value transfer, and the object is still passed as a reference.
Deep cloning: All elements or attributes are completely cloned and the original reference type is completely independent. That is, the original object will not be modified when the attributes of the object are modified later.

The Code is as follows:


Function cloneObject (obj ){
Var o = obj. constructor === Array? []: {};
For (var I in obj ){
If (obj. hasOwnProperty (I )){
O [I] = typeof obj [I] = "object "? CloneObject (obj [I]): obj [I];
}
}
Return o;
}


In addition, for a simple array, the element does not reference the type value, you can directly use array. concat (); or array. slice (0); To copy an array in depth, which is simple and efficient. The concat () and slice () arrays will generate a new array, and the original array will not be affected. However, make sure that the elements in the copied array do not contain reference values.
This is another method of deep cloning, which is very simple and practical:

The Code is as follows:


Var s = JSON. stringify (obj );
Var o = JSON. parse (s );

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.