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