var alpha = { a: 0, b: 0 };
var beta= alpha;
beta.b = 1;
Now alpha.b
is 1.
Why does that happen and what can I do to keep alpha.b
0?
var alpha = { a: 0, b: 0 };
var beta= alpha;
beta.b = 1;
Now alpha.b
is 1.
Why does that happen and what can I do to keep alpha.b
0?
Both alpha and beta are references pointing to the same are in the memory (i.e. the allocated heap). So whenever you change the properties of one object this is instanlty reflected on the other; as they, in essence point to the same object.
What you should instead do copy all the properties from alpha to beta
var alpha = { a: 0, b: 0 },
beta = { };
for(var prop in alpha){
if(alpha.hasOwnProperty(prop)){
beta[prop] = alpha[prop];
}
}
Your object is slightly simple. You can come across a situation where you have nested objects e.g.
var alpha = {
propA: {},
propB: {}
}
In that case you need what is called deep cloning; that is you need to clone recursevely the complex properties.
If you're already using jquery you can leverage the extend
method
$.extend(true, beta, alpha)
alpha
and beta
are variables whose values are references of the same object.
What you want is to clone the alpha object. I guess you'll find many existing implementations now that you know the word to search.
As your question has the JSON tag, I'll just give a simple implementation (doesn't work for cyclic objects) :
var beta = JSON.parse(JSON.stringify(alpha));
Because javascript veriable keeps a reference to an object. You will want to clone an object to break the link to alpha.b.
See: What is the most efficient way to deep clone an object in JavaScript?