pav
6/10/2013 - 8:13 PM

Before we go too much further with Objects, we need to have a little talk about how those variables are stored in memory. Egads!, you say -

Before we go too much further with Objects, we need to have a little talk about how those variables are stored in memory. Egads!, you say - but better now than later.

Say I create another one of those card objects: var card1 = {"suit":"clubs", "rank": 8}

When I do this, I now have a variable card1 that points or 'refers' to the place in memory where the actual object data is stored. When I assign that variable to another variable, I'm really just creating another reference to that same place in memory.

So, if I create another variable called card2 and set it equal to the original card1. var card2 = card1

I now have two variables pointing at the exact same data in memory. If I change a property in either variable, I change them both.

//Here is the original card object
var card1 = {"suit":"clubs", "rank": 8};
//Create a variable named card2 and set it equal to card 1
var card2 = card1
//Change the rank of the card2 variable to 3
card2.rank=3;
//Log the value of the rank property of card 1 to the console
console.log(card1.rank);