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