To understand closures, you should first understand that functions in javascript can be used as variables as below.
Functions as variables
Within the Javascript language, functions are treated as variables. This means that you can pass functions around like variables. which lets you doing something like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Closures
Closures are basicly functions that enclose variables. Here is an example.
1 2 3 4 5 6 7 8 9 |
|
What happens when we execute uselessFunction()? Would localVariable be accessible from function returned by uselessFunction()? It turns out that it is accessible.
uselessFunction(); //Alerts 'WOW! I am Local'
So we see that javascript “closes” in local variables and allows returned functions to access these variables. An example use for this behaviour is described below. This example shows how we can create a custom multiplier.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Notice how 5 gets stored inside the timesFive function and we can reuse the timesFive variable as a function multiple times?
Javascript is whacky and fun!