17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

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

Chapter 13 Scope and Closures<br />

Conceptual overview of <strong>JavaScript</strong> scope<br />

In <strong>JavaScript</strong>, scope is the context in which code is executed. There are three types of<br />

scope: global scope, local scope (sometimes referred to as "function scope"), and eval<br />

scope.<br />

Code defined using var inside of a function is locally scoped, and is only "visible" to<br />

other expressions in that function, which includes code inside any nested/child<br />

functions. Variables defined in the global scope can be accessed from anywhere<br />

because it is the highest level and last stop in the scope chain.<br />

Examine the code that follows and make sure you understand that each declaration of<br />

foo is unique because of scope.<br />

Sample: sample110.html<br />

<br />

var foo = 0; // Global scope.<br />

console.log(foo); // Logs 0.<br />

var myFunction = function () {<br />

var foo = 1; // Local scope.<br />

console.log(foo); // Logs 1.<br />

var myNestedFunction = function () {<br />

var foo = 2; // Local scope.<br />

console.log(foo); // Logs 2.<br />

} ();<br />

} ();<br />

eval('var foo = 3; console.log(foo);'); // eval() scope.<br />

<br />

Make sure you understand that each foo variable contains a different value because<br />

each one is defined in a specifically delineated scope.<br />

113

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

Saved successfully!

Ooh no, something went wrong!