JavaScript Object replication

Source: Internet
Author: User

Recent projects because of fear of data pollution , so the use of JS object replication

JS objects are inherited from object, is a reference type, so can not be copied by the = number

So we have compiled some common methods of replication, as follows

I. Creating a new object through JSON serialization and deserialization

1 var obj = {a:1, B: ' 2 ' }; 2 var newObj = Json.parse (json.stringify (obj));

Test it:

OBJ.A = 3; // obj and NEWOBJ point to different references, so the B property of NEWOBJ does not change console.log (NEWOBJ);
Console.log (obj);

Test results:

However, this method cannot be deeply copied and cannot be copied to the function property. Then we have the following deep copy method.

Second, deep object replication

function Clone (o) {    var s = {};      for (var in o)         typeof O[k] = = = ' object '? Clone (O[k]): o[k];     return s;}

Test a wave:

var obj = {    1,    ' B ',    false,    new Date (),     1 },    function () {Console.log (this. g)},    g: [1, 2]}; var newObj = Clone (obj); Console.log (NEWOBJ);
NEWOBJ.F ();

Test results:

Second, the fast copy of array

Array.prototype.concat can stitch two arrays and return new objects, and with this feature, you can quickly copy an array

var arr1 = [1]; var arr2 = [].concat (ARR1);

Test a wave:

JavaScript Object replication

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.