04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Copying Values<br />

Chapter 4: Variables, Scope, and Memory<br />

Aside from differences in how they are stored, primitive and reference values act differently when<br />

copied from one variable to another. When a primitive value is assigned from one variable to another,<br />

the value stored on the stack is created and copied into the location for the new variable. Consider the<br />

following example:<br />

var num1 = 5;<br />

var num2 = num1;<br />

Here, num1 contains the value of 5. When num2 is initialized to num1 , it also gets the value of 5. This value<br />

is completely separate from the one that is stored in num1 because it ’ s a copy of that value. Each of these<br />

variables can now be used separately with no side effects. This process is diagrammed in Figure 4-2 .<br />

Stack before copy<br />

num1<br />

5<br />

(Number type)<br />

Stack after copy<br />

num2<br />

num1<br />

5<br />

(Number type)<br />

5<br />

(Number type)<br />

Figure 4 - 2<br />

When a reference value is assigned from one variable to another, the value stored on the stack is also<br />

copied into the location for the new variable. The difference is that this value is actually a pointer to an<br />

object stored on the heap. Once the operation is complete, two variables point to exactly the same object,<br />

so changes to one are reflected on the other, as in the following example:<br />

var obj1 = new Object();<br />

var obj2 = obj1;<br />

obj1.name = “Nicholas”;<br />

alert(obj2.name); //”Nicholas”<br />

In this example, the variable obj1 is filled with a new instance of an object. This value is then copied into<br />

obj2 , meaning that both variables are now pointing to the same object. When the property name is set<br />

81

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!