javascript - Two objects with the same value, calculating and changing values of one object. And the second one misteriously has the new values too -


it might late @ night , might become crazy how can be.

i have following scenario:

var x = {a: [], b: []}; var y = {a: [], b: []};  model.somefunction(obj1, function(res){     x.a = res;     y.a = res;     model.somefunction(obj2, function(res){         x.b = res;         y.b = res;          machewasanderes();         // content of both objects:         // x = {a: [punkt1: 20, punkt2: 30}, b: {punkt1: 50, punkt2: 60}]};         // y = {a: [punkt1: 20, punkt2: 30}, b: {punkt1: 50, punkt2: 60}]};     }); });  function machewasanderes(){   for(let prop in x){     for(let = 0; < x[prop].length; i++){         for(let propa in x[prop][i]){             x[prop][i][propa] = x[prop][i][propa] / 100;         }     }   }    console.log("x", x);   console.log("y", y);   // x = {a: [punkt1: 0.02, punkt2: 0.03}, b: {punkt1: 0.05, punkt2: 0.06}]};   // y = {a: [punkt1: 0.02, punkt2: 0.03}, b: {punkt1: 0.05, punkt2: 0.06}]}; } 

as can see receiving data callbacks of model-functions. when these done calling machwasanderes() function in order calculate x object. example changing dividing it's value hundred , saving way.

strangely enough when print out both objects, object y got calculated values...

how can ?

note not exact code. code longer have created simpler copy of code contains issue.

lets goto basics. there 2 types of copies : shallow copy , deep copy.

  1. shallow copy when copy reference other reference , not data. both references pointing same object. means changing 1 object affect on other reference well.
  2. deep copy when create duplicate copy of data , assign reference.

coming case: when

x.a = res; y.a = res; 

both referring same object doing shallow copy. when change x.a, in turn affects y.a well. same goes x.b , y.b

read this.. https://nikhilmachcha.wordpress.com/2015/08/24/deep-copy-vs-shallow-copy-php-way/

hope helps you!!


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -