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.

Sample: sample112.html<br />

<br />

var foo = function () {<br />

var boo = function () {<br />

bar = 2; // No var used, so bar is placed in the global scope at<br />

window.bar<br />

} ();<br />

} ();<br />

console.log(bar); // Logs 2, because bar is in the global scope.<br />

// As opposed to...<br />

var foo = function () {<br />

var boo = function () {<br />

var doo = 2;<br />

} ();<br />

} ();<br />

// console.log(doo); logs undefined. doo is in the boo function scope, so<br />

an error occurs<br />

<br />

The concept to take away here is that you should always use var when defining<br />

variables inside of a function. This will prevent you from dealing with potentially<br />

confusing scope problems. The exception to this convention, of course, is when you<br />

want to create or change properties in the global scope from within a function.<br />

The scope chain (aka lexical scoping)<br />

There is a lookup chain that is followed when <strong>JavaScript</strong> looks for the value associated<br />

with a variable. This chain is based on the hierarchy of scope. In the code that follows, I<br />

am logging the value of sayHiText from the func2 function scope.<br />

Sample: sample113.html<br />

<br />

var sayHiText = 'howdy';<br />

var func1 = function () {<br />

var func2 = function () {<br />

console.log(sayHiText); // func2 scope, but it finds sayHiText in<br />

global scope.<br />

} ();<br />

115

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

Saved successfully!

Ooh no, something went wrong!