There is no direct way to provide object cloning in JavaScript. So when you change object B in the code below, it changes the object A.
A = {k1:1, k2:2, k3:3};b = A;B.K2 = 4;
If you want to change only B and keep a constant, you need to copy object A.
Object copying with jquery
In the case of jquery, jquery's own extend
method can be used to implement object replication.
A = {k1:1, k2:2, k3:3};b = {};$.extend (b,a);
Customizing the Clone () method to implement object replication
The following method is the basic idea of object replication.
Object.prototype.clone = function () {var copy = (this instanceof Array)? [] : {}; For (attr in this) {if (!obj.hasownproperty (attr)) continue; COPY[ATTR] = (typeof this[i] = = "Object")? Obj[attr].clone (): obj[attr]; } return copy;}; A = {k1:1, k2:2, k3:3};b = A.clone ();
The following example is considered more comprehensive and applies to deep copy of most objects.
Function clone (obj) { // handle the 3 simple types, and null or undefined if (null == obj | | "Object" != typeof obj) return obj; // Handle date if (obj instanceof date) { var copy = new date (); Copy.settime (Obj.gettime ()); return copy; } // Handle Array if (obj Instanceof array) { var copy = []; for (var i = 0, var len = obj.length; i < leN; ++i) { copy[i] = clone (Obj[i]); } return copy; } // Handle Object if (Obj instanceof object) { var copy = {}; for (var attr in obj) { if ( Obj.hasownproperty (attr)) copy[attr] = clone (obj[attr]); } return copy; } throw new error ("Unable to copy obj! its type isn ' t supported. ");
network resources
Object cloning in JavaScript