Tuesday, September 7, 2010

JavaScript concepts part 4 - closures

Introduction

JavaScript is a language that's widely used across the web, but it's often not deeply used by many of the page authors writing it. So in this "JavaScript concepts series" I try to introduce some of the deeper concepts of the JavaScript language. This is last article in this short tutorial.

Closures

To people programming in traditional OO or procedural languages, closures are often an add concept to grasp. While to those programmers with functional programming background, they're really natural and cozy concept.

Stated as easy as possible, a closure is a Function instance coupled with the local variables that are not declared in function inner scope, but in outer scope (an outer scope of the function if you know what I mean). So they are just Functions + local variables, no more and no less. Put this all in dynamic environment and you get some powerful concept for handling asynchronous callbacks.

When function is declared, it has the ability to reference any variables that are in its scope (in scope that function has access to) at the point of the declaration. This is off course all familiar, but catch is that this "outer" variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration.
This ability is essential tool for writing effective JavaScript code. Consider following example:

var local = 1;
window.setInterval(function() {
alert(local);
local++;
},
3000);

In example we declare local variable (named "local") and assign number to it. We then use timer function ("setInterval") to establish a timer that will fire every 3 seconds. As the callback for timer, we specify an inline function that references local "local" variable and shot its value. Also we increment that variable in body of the function.

So what happen here. We might assume that because the callback will fire off three seconds after the page loads, the value of the local "local" variable will be undefined. After all, the block in which "local" is declared goes out of scope when page finished loading, because the script in header (or else on the page) finished executing? But it works!

Although it is true that the block in which "local" is declared goes out of scope when page finished loading, the closure created by the declaration of the function + variable "local" stays in scope for lifetime of the function. So, woala!

This is the end of this series, I hope you learn something useful and interesting.

No comments:

Post a Comment