javascript - Node.js What is object Cloning? -
i want know why have clone objects instead of direct assigning.
var obj1 = {x: 5, y:5}; var obj2 = obj1; obj2.x = 6; console.log(obj1.x); // logs 6
i got solution want know why obj2 working reference variable ?
let's @ code step step:
1 -
var obj1 = {x: 5, y:5};
create object {x: 5, y:5}
, store reference in variable obj1
2 -
var obj2 = obj1;
create variable obj2
, attribute value of obj1
it. value of obj1
reference object, obj2
pointing same object.
3 -
obj2.x = 6;
change value of property x
in object being referenced
4 -
console.log(obj1.x); // logs 6
print x
property object being referenced obj1
. obj1
, obj2
pointing @ same place, output 6
.
this same behavior language works references objects have. java, c, c++, c#, etc. in oop languages have clone()
method field field copy. in case of js, such method doesn't exist, need deep copy of every element. can find nice set of answers regarding how clone elements in js here: what efficient way deep clone object in javascript?
Comments
Post a Comment