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.

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

on obj1 , it can later be accessed from obj2 because they both point to the same object. Figure 4 - 3 shows<br />

the relationship between the variables on the stack and the object on the heap.<br />

Stack before copy<br />

Heap<br />

Object<br />

obj1<br />

(Object type)<br />

Object<br />

Stack after copy<br />

Object<br />

obj2<br />

(Object type)<br />

Object<br />

obj1<br />

Figure 4 - 3<br />

(Object type)<br />

Argument Passing<br />

All function arguments in ECMAScript are passed by value. This means that the value outside of the<br />

function is copied into an argument on the inside of the function the same way a value is copied from<br />

one variable to another. If the value is primitive, then it acts just like a primitive variable copy, but if the<br />

value is a reference, it acts just like a reference variable copy. This is often a point of confusion for<br />

developers because variables are accessed both by value and by reference, but arguments are passed<br />

only by value.<br />

When an argument is passed by value, the value is copied into a local variable (a named argument or, in<br />

ECMAScript, a slot in the arguments object). When an argument is passed by reference, the location of<br />

the value in memory is stored into a local variable, which means that changes to the local variable are<br />

reflected outside of the function. Consider the following example:<br />

function addTen(num) {<br />

num += 10;<br />

return num;<br />

}<br />

var count = 20;<br />

var result = addTen(count);<br />

alert(count); //20 - no change<br />

alert(result); //30<br />

82

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

Saved successfully!

Ooh no, something went wrong!