Learning Ext JS 3

What are the Closures? Más videos

Descripción del tema

With closures we can solve a lot of problems when we develop components or applications, it is important to understand this concept. 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.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

2Comentarios

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Regístrate a este curso

Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

Tendrás acceso a descargar los videos, códigos y material adicional.

Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

Llevarás un registro de tu avance.