JavaScript does not directly provide a method for object replication (the object clone). So when you change object B in the following code, you change object A.
A = {k1:1, k2:2, k3:3};
b = A;
B.K2 = 4;
If you just want to change B and keep a unchanged, you need to copy object A.
Using jquery for Object replication
With jquery, the Extend method of jquery can be used to replicate objects.
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 is suitable for deep replication of most objects (Deep copy).
function Clone (obj) {
//Handle The 3 simple types, and null or undefined
if (null = obj | | "Object"!= typeof obj) return to 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. ');
The above in-depth understanding of the object of JavaScript in the replication of objects (object Clone) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.