Blog

ExtJS and Sencha Touch Themes and Templates

What are the Closures?

Mar 19, 2009 | English | By | 1 Comment | Leer en Español

With closures we can solve a lot of problems when we develop components or applications, it is important to understand this concept.

What are the Closures?
Author: Crysfel

I'm a software developer with 6+ years of experience, when I'm not developing software I may be writing a tutorial, you can follow me on twitter

Closures are the way where inner functions can refer to the variables contained in their outer enclosing function after their parent functions have already terminated. This concept can be a little hard to comprehend and explain so let’s see an example to fully understand it:

function sayHi(seconds){
	var hi = 'Hi folks!';

	setTimeout(function(){
		console.info(hi); //Referring to the variable "hi"
	},seconds*1000);
}

sayHi(2);

In the previous example we can clearly see when the function “sayHi” stops executing, after 1 second the inner function is executed showing the text of the variable “hi”, which belongs to the parent function, this is a closure.

Hiding global variables

Many times we declare variables in the “global scope”, this is consider to be a bad practice because these variables can interfere with some libraries or code from another member of our team. If we use a self-executing anonymous function and we use closures we can solve this problem easily, the next example shows how to do that:

(function(args){
	var thisWasGlobal = 'closure!';

	window.onload = function(){
		console.info(thisWasGlobal);
	}

})();

The previous code encapsulates the variables that are declared inside of the anonymous function, in this way the variables will be in a different scope where there’s no danger that they will overwrite other variables.

Closures and Scope

We have seen that a closure allows us to refer variables that exist and belong to the parent function, it is important to remember that when you do a closure, it will take the last value of the variable defined in the parent function. A common case is when we have a loop, let’s see the next example:

window.onload = function(){
	var el = document.getElementById('element');
	var events = ['click','mouseover','mouseout'];

	for(var i=0;i<events.length;i++){
		var item = events[i];
		el['on'+item] = function(){
			console.info('event: '+item);
		}
	}
}

When we run the previous code, the events contained in the array “events” are added to the selected element, but you can see that there is a problem when the events are printed in the console, because the same event is printed, in this case “mouseout”, this happens because the variable “item” contains “mouseout” as the last value assigned.

To solve this problem we need to create a different scope for each iteration of the loop, in this way different variables will be created; this can be done via an anonymous function that will auto run. If you have any questions of the concept scope I recommend you to read the previous chapter of the course. The code will be like this:

window.onload = function(){
	var el = document.getElementById('element');
	var events = ['click','mouseover','mouseout'];

	for(var i=0;i<events.length;i++){
		(function(){ //the anonymous function creates a new scope
			var item = events[i]; //item belongs to the anonymous function
			el['on'+item] = function(){
				console.info('event: '+item); //a closure of the anonymous function
			}
		})();
	}
}

If we execute the previous code we will see that the correct events are printed in the console.

Conclusions

In this chapter we have learned what is a closure and how useful it is when we introduce the concept scope, this is something we must learn and remember when we are developing our applications.

The topic closure is complicated, I recommend you to have a quick look at the article “JavaScript Closures” written by Jim Jey, it is an excellent resource you must have.

As always you can leave your questions or suggestions in the comments section and don’t forget to vote for us in your favorite social network.

One Response to “What are the Closures?”

  • Jack Aug 13, 2010

    Thanks for doing up these tutorials!

Leave a Reply







Updates

RSS

Subscribe to our feeds to receive updates of our newest posts and free tutorials.

Site search

Maybe we have what you need, would you like to search first?

Donations

Would you buy me a cup of coffee? I am sharing my knowledge and time with you, help this project grow. Thank you!