First look at an example:
1 var student = {2 name: "Yxz",3 age:254} 5 var newstudent = student; 6 newstudent.sex = "male"; 7 // {name: "Yxz", Age:25,sex: "Male"}
Thus, when passing an object through a simple pass assignment to a new variable, it simply adds an alias to the object. Therefore, the operation of the alias will also affect the original object, so by Newstudent.sex to the object student Add properties can be implemented. However, more often we want the newstudent and student objects to be independent, then we need to generate a copy of the original object, see the following example:
1 varCloneobj =function(obj) {2 varstr, newobj = Obj.constructor = = = Array? [] : {};3 if(typeofObj!== ' object '){4 return; 5} else if (window. JSON) {6 str = json.stringify (obj),//Serialization of object 7 newobj = Json.parse (str);//restore 8} else {9 for ( var i in obj) {newobj[i] = typeof obj[i] = = = ' object '? Cloneobj (Obj[i]): Obj[i];}12} - returnnewobj; - }; the //Test - varStudent = { -Name: "Yxz", -Age:25, +Sex: "Male" - }; + //perform a deep clone A varNewstudent =cloneobj (student); at DeleteNewstudent.sex; -Console.log (newstudent);//{name: "Yxz", age:25} -Console.log (student);//{name: "Yxz", Age:25,sex: "Male"}
By executing the results you can see that newstudent has become a cloned copy, and any action on newstudent will no longer affect the student object.
Note: Json.stringify and parse are JSON object serialization and deserialization functions, which are responsible for serializing the object into a string and deserializing the JSON string into an object, because this belongs to the ECMASCRIPT5 specification, so the red part of the program does a compatible processing.
JS Object Deep Clone