06.07.2017 Views

Mastering JavaScript

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

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

Chapter 2<br />

Were you expecting something shiny? No, this is really the most ordinary case of a<br />

closure. We are declaring a variable in the global scope and declaring a function in<br />

the global scope. In the function, we are able to access the variable declared in the<br />

global scope—outer. So essentially, the outer scope for the outerFn() function is a<br />

closure and always available to outerFn(). This is a good start but perhaps then you<br />

are not sure why this is such a great thing.<br />

Let's make things a bit more complex:<br />

var outer = 'Outer'; //Variable declared in global scope<br />

var copy;<br />

function outerFn(){ //Function declared in global scope<br />

var inner = 'Inner'; //Variable has function scope only, can not be<br />

//accessed from outside<br />

function innerFn(){ //Inner function within Outer function,<br />

//both global context and outer<br />

//context are available hence can access<br />

//'outer' and 'inner'<br />

console.log(outer);<br />

console.log(inner);<br />

}<br />

copy=innerFn;<br />

//Store reference to inner function,<br />

//because 'copy' itself is declared<br />

//in global context, it will be available<br />

//outside also<br />

}<br />

outerFn();<br />

copy(); //Cant invoke innerFn() directly but can invoke via a<br />

//variable declared in global scope<br />

Let's analyze the preceding example. In innerFn(), the outer variable is available<br />

as it's part of the global context. We're executing the inner function after the outer<br />

function has been executed via copying a reference to the function to a global<br />

reference variable, copy. When innerFn() executes, the scope in outerFn() is gone<br />

and not visible at the point at which we're invoking the function through the copy<br />

variable. So shouldn't the following line fail?<br />

console.log(inner);<br />

[ 67 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!