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?

3 Answers3

4

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)
ppoliani
  • 4,792
  • 3
  • 34
  • 62
2

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));
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    An explanation as to why this is happening may be helpful to the OP. – Jeff Shaver Feb 12 '14 at 13:16
  • It can work for cyclic objects using a replacer however. – plalx Feb 12 '14 at 13:25
  • @plalx Yes (see my [related question](http://stackoverflow.com/questions/13861254/json-stringify-deep-objects)) but it's much more expensive. And it still doesn't work with very big objects (like `window`). – Denys Séguret Feb 12 '14 at 13:26
0

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?

Community
  • 1
  • 1
spassvogel
  • 3,479
  • 2
  • 18
  • 23