Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript : changing value of parent when child is changed

One fine day, Every thing was moving smoothly,Until  a basic assignment operation failed.

a = { "val" : 10}
{val: 10}
b = a
{val: 10}
b.val = 30
30
a -> {val: 30}

A basic operation where assigning value made me debug everything for hours.

Later I found, As the value of a which was assigned to b. Any change in b is reflected to a at the same time.

Well it was the reference of Object in b that was working as a pointer to a and thus changing its value.

How to solve this??  Just destroy the instance of that object. 

How i Did?

b = JSON.stringify(a)
"{"val":30}"
// this destroyed the object and all its reference.
JSON.parse(b)
{val: 30}  // here the object is in original state.
b.val = 40 // assigned new value to b
40  
a
{val: 30} // value of a is no changed

this is not a big issue but for people who are new with Javascript, this can be a pain .



This post first appeared on Web Service Testing A Blackjack GUI And API, please read the originial post: here

Share the post

JavaScript : changing value of parent when child is changed

×

Subscribe to Web Service Testing A Blackjack Gui And Api

Get updates delivered right to your inbox!

Thank you for your subscription

×