JAVASCRIPT OBJECTS - Copying by Value vs. Copying by Reference
copy by valuevar myArmor = "Helmet";
alert (myArmor); var myNewArmor = myArmor; alert (myNewArmor); var myNewArmor = "Breastplate"; alert (myNewArmor); var myNewArmor = myArmor; alert (myNewArmor); Let's look one line at a time. I assigned Helmet myArmor variable. My output was Helmet. Then I created a new variable myNewArmor and gave the same value of myArmor. My output was Helmet again. Then I gave a new value to myNewArmor. My output was a Breastplate. Then I gave myNewArmor the same value as myArmor. My output was Helmet. You should get Helmet Helmet Breastplate and Helmet.
|
COPY BY referenceHere we have an object myOldArmor. One of the key pairs has a weapon "This is my old Medieval Sword".
var myOldArmor = { weapon: "This is my old Medieval Sword" }; alert(myOldArmor.weapon); The output yields "This is my old Medieval Sword" var myNewArmor = myOldArmor; alert(myNewArmor.weapon); The output yields "This is my old Medieval Sword" myNewArmor.weapon = "I got my new Viking Sword"; alert(myOldArmor.weapon); The output yields "This is my new Viking Sword" alert(myNewArmor.weapon); The output yields "This is my new Viking Sword" As you can see there is a difference between copy value vs. copy by reference. |