15/8/2 object Simple, deep cloning (replication)

Source: Internet
Author: User

Reference: http://qianduanblog.com/post/js-learning-30-object-clone-copy.html

base data type: Boolean/number/string

var a= ' a '; var b;b=a;b= ' B '; Console.log (a); Console.log (b);

Cloning of a basic data type is a direct clone of an object, both of which are worth passing, and are not linked after cloning

Reference data type: Array/object/function

Cloning of arrays

var a = [1,2];var b;b = a;b[2] = 3;console.log (a);    {A-i}

  This normal clone can see that both control the same object, which is the feature of the reference type. Two sets of unrelated arrays can be cloned by looping.

var a = [1,2];var b = [];var i = 0;var j = a.length;for (; i<j;i++) {  b[i] = A[i];            }  B.push (3); Console.log (b);  {1,2,3}console.log (a); {A}

  

Because arrays are also objects, the clones and arrays of objects are the same

var a = {1: ' One ', 2: '}var b = {};for (var i in a) {    b[i] = a[i];} Console.log (b);     Object {1: "One", 2: "}b[3") = ' three '; Console.log (b);    Object {1: "One", 2: "Three"}console.log (1);    Object {1: "One", 2: "One"}

  

the cloning of a function is special: the cloning of a function, using the "=" symbol, and changing the cloned object will not affect the object before cloning, because the cloned object will be copied once and store the actual data, is the real clone.

var x=function () {alert (1);}; var y=x;y=function () {alert (2);};/ /function () {alert (1);}; alert (x);//Y=function () {alert (2);}; alert (y);
   Complete object cloning:

The complete object cloning requires the type judgment of the parameters, which is a comprehensive application.

15/8/2 object Simple, deep cloning (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.