17.11.2015 Views

JavaScript_Succinctly

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

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

The concept to take away here is that complex values are a composite of values and<br />

differ in complexity and composition to primitive values.<br />

Notes<br />

The term "complex object" has also been expressed in other writings as "composite<br />

objects" or "reference types.” If it's not obvious, all these names describe the nature of a<br />

<strong>JavaScript</strong> value excluding primitive values. Primitive values are not "referenced by<br />

value" and cannot represent a composite (i.e. a thing made up of several parts or<br />

elements) of other values, while complex objects are "referenced by value" and can<br />

contain or encapsulate other values.<br />

How complex values are stored/copied in <strong>JavaScript</strong><br />

It is extremely important to understand that complex values are stored and manipulated<br />

by reference. When creating a variable containing a complex object, the value is stored<br />

in memory at an address. When you reference a complex object, you’re using its name<br />

(i.e. variable or object property) to retrieve the value at that address in memory. The<br />

implications are significant when you consider what happens when you attempt to copy<br />

a complex value. In the next sample, we create an object stored in the variable<br />

myObject. The value in myObject is then copied to the variable copyOfMyObject.<br />

Really, it is not a copy of the object—more like a copy of the address of the object.<br />

Sample: sample18.html<br />

<br />

var myObject = {};<br />

var copyOfMyObject = myObject; // Not copied by value, just the reference<br />

is copied.<br />

myObject.foo = 'bar'; // Manipulate the value stored in myObject.<br />

/* If we log myObject and copyOfMyObject, they will have a foo property<br />

because they reference the same object. */<br />

console.log(myObject, copyOfMyObject); // Logs 'Object { foo="bar"}<br />

Object { foo="bar"}'<br />

<br />

What you need to realize is that, unlike primitive values that would copy a value, objects<br />

(aka complex values) are stored by reference. As such, the reference (aka address) is<br />

35

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

Saved successfully!

Ooh no, something went wrong!