Java Reference
In-Depth Information
A closure is a reference to a free variable that was created inside the scope of another
function, but is then kept alive and used in another part of the program. They're one of
JavaScript's most powerful features, but they can be difficult to get your head round initially.
Function Scope
Back in Chapter 4 , we saw that the value of a variable was only available inside the body
of a function if the var keyword was used. In the following example, there are two vari-
ables: global , which is available everywhere, and local , which is only available inside
the function:
var outside = "I'm a global variable";
function fun() {
var inside = "I'm a global variable";
<< "I'm a global variable"
<< Error: "local is not defined"
It appears that we're unable to access the variable local outside of the function. It turns
out, however, that we can gain access to it outside of its function using a closure.
The Ninja Training Temple
Imagine a temple where people go to train to be a ninja. When they enter the temple, new
ninjas learn how to use weapons. Once they have mastered these skills, they move into the
inner sanctum to learn about the skills of stealth. A person who has never entered the temple
has neither the weapons nor stealth skills. A ninja who is inside the temple but not the in-
ner sanctum only knows about the weapon skills. Once ninjas enters the inner sanctum they
learn the stealth skills and still have the weapons skills. This can be represented by the fol-
lowing function:
Search WWH ::

Custom Search