14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

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

APPENDIX A ■ Debugging <strong>JavaScript</strong><br />

Trying to Access Undefined Variables<br />

I talked about it in the second chapter of the book: you define variables either by declaring them <strong>with</strong> or <strong>with</strong>out<br />

an additional var keyword. (The latter is necessary to define the scope of the variable.) Keep in mind that strict<br />

mode will prevent you from implicitly declaring variables (variables <strong>with</strong>out the var keyword). Because of this, it is<br />

recommended that you use the var keyword for every variable.<br />

Stewie = "Son of Peter <strong>and</strong> Lois";<br />

var Chris = "Older Son of Peter <strong>and</strong> Lois";<br />

If you try to access a variable that hasn’t been defined yet, you’ll get an error. The alert() in the following script<br />

throws an error because Meg is not defined yet:<br />

Peter = "The Family Guy";<br />

Lois = "The Family Guy's Wife";<br />

Brian = "The Dog";<br />

Stewie = "Son of Peter <strong>and</strong> Lois";<br />

Chris = "Older Son of Peter <strong>and</strong> Lois";<br />

alert( Meg );<br />

Meg = "The Daughter of Peter <strong>and</strong> Lois";<br />

This is easy when it is an obvious example like this one, but how about trying to guess where the bug in the<br />

following example is?<br />

exampleFamilies.html<br />

function getFamilyData( outptID, isTree, familyName ) {<br />

var father, mother, child;<br />

switch( familyName ) {<br />

case 'Griffin':<br />

father = "Peter";<br />

mother = "Lois";<br />

child = "Chris";<br />

break;<br />

case 'Flintstone':<br />

father = "Fred";<br />

mother = "Wilma";<br />

child = "Pebbles";<br />

break;<br />

}<br />

var out = document.getElementById( outputID );<br />

if( isTree ) {<br />

var newUL = document.createElement( 'ul' );<br />

newUL.appendChild( makeLI( father ) );<br />

newUL.appendChild( makeLI( mother ) );<br />

newUL.appendChild( makeLI( child ) );<br />

out.appendChild( newUL );<br />

} else {<br />

var str = father + ' ' + mother + ' ' + child;<br />

out.appendChild( document.createTextNode( str ) );<br />

}<br />

}<br />

getFamilyData( 'tree', true, 'Griffin' );<br />

344<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!