Ad

Ad

Sunday, 4 May 2014

JavaScript Closures

JavaScript variables can belong to the local or global scope.
Private variables can be made possible with closures.

Global Variables

A function can access variables defined outside the function, like this:

Example

var a = 4;
function myFunction() {
  return a * a;
}

Try it Yourself »
A function can access a variables defined inside the function, like this:

Example

function myFunction() {
  var a = 4;
  return a * a;
}

Try it Yourself »
In the first example, a is a global variable.
In a web page, a global variable belongs to the window object. It can be used (and changed) by all scripts in the page (in the window).
In the second example, a is a local variable.
A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.
Global and local variables with the same name are different variables. Modifying one, does not modify the other.
NoteVariables created without the keyword var, are always global, even if they are created inside a function.


Variable Lifetime

Global variables live as long as your application lives (your window / your web page).
Local variables have short lives. They are created when the function is invoked, and deleted when the function exits.

A Counter Problem

Suppose you want to use variable for counting something, and you want this counter to be available to all functions.
You could use a global variable, and a function to increase the counter:

Example

var counter = 0;

function add(x) {
  counter += x;
}

add(10);
add(15);
add(20);

// the counter is now equal to 45

Try it Yourself »
The counter should only be changed by the add() function.
The problem is, that any script on the page can change the counter, without calling add().
If I declare the counter inside the function, nobody will be able to change it without calling add():

Example

function add(x) {
  var counter = 0;
  counter += x;
}

add(10);
add(15);
add(20);

// the counter should now be 45, but it does not work ! 

Try it Yourself »
Help! It did not work!
Every time a call the add() function, the counter is reset.
How can I solve this?

JavaScript Closures

Remember self-invoking functions? What does this function do? At least it preserves the counter:

Example

var add = (function () {
    var counter = 0;
    return function (x) {return counter += x}
}())

add(10);
add(15);
document.getElementById("demo").innerHTML = add(20);

// the counter is now 45

Try it Yourself »
In the example above, add is assigned to the return value of a self invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
The counter is protected by the scope of the anonymous function, and can only be changed using the add function.
NoteA JavaScript closure is a function having access to the scope the parent function, after the parent function has returned.

No comments:

Post a Comment