04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

All variables, primitive and reference, exist within an execution context (also called a scope), that<br />

determines the lifetime of the variable and which parts of the code can access it. Execution context can be<br />

summarized as follows:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

Execution contexts exist globally (called the global context) as well as within functions.<br />

Each time a new execution context is entered, it creates a scope chain to search for variables and<br />

functions.<br />

Contexts that are local to a function have access not only to variables in that scope, but also to<br />

variables in any containing contexts as well as the global context.<br />

The global context has access only to variables and functions in the global context and cannot<br />

directly access any data inside local contexts.<br />

The execution context of variables helps to determine when memory will be freed.<br />

JavaScript is a garbage - collected programming environment where the developer need not be concerned<br />

with memory allocation or reclamation. JavaScript ’ s garbage - collection routine can be summarized as<br />

follows:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

Values that go out of scope will automatically be marked for reclamation and will be deleted<br />

during the garbage - collection process.<br />

The predominant garbage - collection algorithm is called mark - and - sweep, which marks values<br />

that aren ’ t currently being used and then goes back to reclaim that memory.<br />

Another algorithm is reference counting, which keeps track of how many references there are to<br />

a particular value. JavaScript engines no longer use this algorithm, but it still affects IE due to<br />

non - native JavaScript objects (such as DOM elements) being accessed in JavaScript.<br />

Reference counting causes problems when circular references exist in code.<br />

Dereferencing variables helps not only with circular references but also with garbage collection<br />

in general. To aid in memory reclamation, global objects, properties on global objects, and<br />

circular references should all be dereferenced when no longer needed.<br />

95

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

Saved successfully!

Ooh no, something went wrong!