04.11.2015 Views

javascript

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

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

Mimicking Block Scope<br />

Chapter 7: Anonymous Functions<br />

As mentioned previously, JavaScript has no concept of block - level scoping, meaning variables defined<br />

inside of block statements are actually created in the containing function, not within the statement.<br />

Consider the following:<br />

function outputNumbers(count){<br />

for (var i=0; i < count; i++){<br />

alert(i);<br />

}<br />

}<br />

alert(i);<br />

//count<br />

In this function, a for loop is defined and the variable i is initialized to be equal to 0. For languages such<br />

as Java and C++, the variable i would be defined only in the block statement representing the for loop,<br />

so the variable would be destroyed as soon as the loop completed. However, in JavaScript the variable i is<br />

defined as part of the outputNumbers() activation object, meaning it is accessible inside the function<br />

from that point on. Even the following errant redeclaration of the variable won ’ t wipe out its value:<br />

function outputNumbers(count){<br />

for (var i=0; i < count; i++){<br />

alert(i);<br />

}<br />

}<br />

var i; //variable redeclared<br />

alert(i); //count<br />

JavaScript will never tell you if you ’ ve declared the same variable more than once; it simply ignores all<br />

subsequent declarations (though it will honor initializations). Anonymous functions can be used to<br />

mimic block scoping and avoid such problems.<br />

The basic syntax of an anonymous function used as a block scope (often called a private scope ) is as<br />

follows:<br />

(function(){<br />

//block code here<br />

})();<br />

This syntax defines an anonymous function that is called immediately. The function declaration is<br />

enclosed in parentheses to indicate that it ’ s actually a function expression. This function is then called via<br />

the second set of parentheses at the end. If this syntax is confusing, consider the following example:<br />

var count = 5;<br />

outputNumbers(count);<br />

191

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

Saved successfully!

Ooh no, something went wrong!