Work accumulation (Iv.) implementation of--javascript deep cloning

Source: Internet
Author: User

There are two large classes of data in JavaScript, the base type and the reference type. Because reference types use pointers, cloning is not possible at simple assignments, and two methods are described below to implement JavaScript deep cloning.

1. native JavaScript:

function clone (former)  {if (! ( Former instanceof object)  | | former === null | |   (FORMER INSTANCEOF REGEXP)  | |   (former instanceof function)  return former;         if (Former instanceof array)  {             return former.slice ();        }         var latter = {};         for (Var attr in former)  {             latter[attr] = clone (former[attr]);         }        return latter;} 

whereformer is the parameter passed in , latter is the parameter returned after cloning, if we now have the following obj1 object:

var obj1 = {"Name": "Lucy", "boyfriend": null, "Measurements": [100,80,90], "Sayhi": function () {Console.log ("hi~")}};

now clone the obj1 depth to obj2 to detect if two objects are the same:

var obj2 =clone (obj1); obj1 = = = OBJ2//False

If we simply assign a value, we'll check if two objects are the same:

var obj3 = obj1;obj1 ===obj3//True

2.jQuery API :

JQuery has encapsulated a method for us to implement deep cloning, which is jquery.extend ([deep], Target, Object1, [objectn]) . Of course, the method according to the parameters received a lot of different uses, here we do not delve into, simply look at how to use it to achieve deep cloning. Or the previous obj1 object, like cloning it to obj4 :

var obj4 = {};jquery.extend (true, Obj4, obj1); obj1 = = OBJ4//False

end.

The JQuery API can refer to the following links:

http://www.php100.com/manual/jquery/

This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1658932

Work accumulation (Iv.) implementation of--javascript deep cloning

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.