Closures
Closures
Closures can be a slightly confusing topic for some, but more than likely you will find yourself using them in the course of your JavaScript coding without realizing. jQuery makes heavy use of closures. A closure is an inner function that can access the outer functions’ variables. Just as we mentioned earlier in this chapter, a variable has a global scope or a function scope. The closure, being within a function, can access both of these scopes, as well as its own inner scope. Furthermore, the closure can access the outer functions’ parameters. Let’s investigate this with a simple code example where two closures provide functionality to calculate the area of a circle or a rectangle.
function calculateArea(height, width, shape){
var pi = Math.PI;
//first closure
function getCircleArea(){
var circleArea = pi * (height*height);
return circleArea;
}
//second closure
function getRectangleArea(){
var area = width * height;
return area;
}
if(shape === 'Circle'){
return getCircleArea();
}
else{
return getRectangleArea();
}
}
So, you’re creating a closure any time you define a function within another function. This could be thought of as an object with just one method and that method is private because it can’t be executed from outside of that function.