JavaScript summed up #2: Closures
Closures are a vital part of JavaScript’s dynamic nature. Without it, a lot of things would work totally different. Because of this significance, it’s important to thoroughly understand closures.
So, what _is_ a closure, really?
- A closure simply is a function inside of another function (an inner function, if you will)…
- …that has access to the context of its outer/enclosing function…
- [now it gets interesting!] …even if the outer function has already terminated.
Okay, let’s have an example:
var myFunction = function(text){
setTimeout( function(){
alert(text);
}, 1000);
}
Here, the case is quite clear: when the inner function is called through the timeout, the outer function (”myFunction”) has long terminated (about 1 sec. ago). Still, the inner function has access to the variables of its parent function (the variable “text”, in this case).
Some more examples should make the use and importance of closures a little clearer:
(function(){})();
Used in many modern AJAX libraries, this construct can be quite puzzling on first sight. So let’s deconstruct it outside-in, to see what’s it all about.
The (…)() construct is used to hide the contained code from the outside world (and scope). Try this example for yourself:
function testFunc(){};
(function test2Func(){});
console.log(window.testFunc);
console.log(window.test2Func);
The first one, testFunc, is visible to the outside world (window.x), the second is hidden from it. So (…)() can be used to avoid polluting the global namespace.
The anonymous function inside of the parentheses is used to create and execute the desired code in one go. Additionally, we have access to all outside variables – because a function always has access to it’s surrounding context.
private variables
As you probably know, the JavaScript language currently doesn’t have the concept of public/private/protected members. But with closures, we can simulate this system:
function publicPrivate(){
var privateProp = "This one is private";
var privateFunc = function(){ console.log("From private func:", privateProp); };
privateFunc();
return {
publicProp: "This one is public"
}
}
var myObj = new publicPrivate();
console.log("From outside:", myObj.publicProp);
console.log("From outside:", myObj.privateProp);
The last console.log will return undefined in Firebug, because privateProp can’t be accessed from outside. The first one, from inside our publicPrivate function, will return “This is private” because we’re calling our private member from inside.





0 comments
Kick things off by filling out the form below.
Leave a Comment