Javascript deep copy

Source: Internet
Author: User

Let's take a look at the defects of the shortest replication. I don't know how many people have done it? CopyCode The Code is as follows: var ooriginal = {
Memnum: 1, // number
Memstr: "I am a string", // string
Memobj :{
Test1: "old value" // We'll test
},
Memarr: [// Array
"A string", // string member of Array
{// Object member of Array
Test2: "try changing me" // We'll test
}
]
};

This is a complex object that contains objects and arrays. Let's take a look at the complexity of the famous inheritance function of prototype. It is hard to say that it is inheritance, and jquery does not.Copy codeCode: var extend = function (result, source ){
For (var key in source)
Result [Key] = source [Key];
Return result;
}

TestProgram:Copy codeThe Code is as follows: var ocopy = extend ({}, ooriginal); // light copy
Ocopy. memobj. test1 = "New Value"; // if a problem occurs, it is reflected to the original object.
Alert (ooriginal. memobj. test1); // The result copy is modified together with the original one.
Ocopy. memarr [1]. Test2 = "I am changed ";
Alert (ooriginal. memarr [1]. Test2 ); //

Lang = "en">


Javascript deep copy by situ zhengmei

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.