Learning Ext JS 3

The context and the variable "this" Más videos

Descripción del tema

The context is the object that is operating at the time of execution, in JavaScript your code will always have a context. This chapters shows how we can change or assigned the context to methods or functions.

The context

The context works through the variable "this", which refers to the object that is contained in the code that is being executed. In previous chapters we talked about the "global scope", who is contained in the object "window", so if you print the variable "this" in the Firebug console, the object "window" will be displayed.
// this == window
console.debug(this);

function test(){
	// this == window
console.debug(this);
}

test();
The function "test" created a new scope but we didn't specify a context in where it should run, therefore it takes the global context and the variable "this" inside of the function "test" scope points to the object "window", this is why when we print in the console the variable "this", the object "window" is shown. Let's see an example of a function within the context of an object.
var obj = {
	name: 'obj',
	run: function(){
		// this == obj
		this.value = 1;
		console.debug(this.name);
	}
};

obj.run();
In the previous code we can see that through the keyword "this" we can reference the object "obj", this is how we can add properties to the object or read properties of the object.

Changing the context of a function

When you create an anonymous function or a function inside of a method of the object "obj", they have a different context because those functions use the global context, unless you assign one. Let's see the next example:
var obj = {
	name: 'obj',
	run: function(){
		this.value = 1;
		console.debug(this); // this == obj
		
		(function(){ // a new scope is created
			console.debug(this); // this == window
		})();
		
		function test(){ // a new scope is created
			console.debug(this); // this == window
		}
		
		test();
	}
};

obj.run();
As you can see the variable "this" that is inside of the anonymous function and the "test" function points to the object "window" instead of the object "obj", this happens because these functions haven't been defined as methods of the object "obj", therefore they don't belong to "obj" and adopt the global context. In the next example we have the same code with a small change in the anonymous function and the "test" function:
var obj = {
	name: 'obj',
	run: function(){
		this.value = 1;
		console.debug(this); // this == obj
		
		(function(){
			console.debug(this); // this == obj
		}).call(this); // it is self executed with the method call
		
		this.test = function(){ // it is defined as a method of obj
			console.debug(this); // this == obj
		}
		
		this.test(); // it is executed inside of the context obj
	}
};

obj.run();
In the anonymous function we are using the method "call" so it can be self-executed and we pass as a parameter the object that it will use as context in the moment when is being executed, in this way we have changed the global context, that we previously had for the "obj" context. We have changed the way the function "test" was defined and now we define it as a method of the object "obj", in this way it will be executed in the same context of the object "obj". The function call was changed too, since now we preceded the variable "this" to the method "test". There's another method to change the context of a function and it is call "apply", this method receives in the first parameter the object that will use as the context when is executed and in the second parameter an array of the parameters that we need to pass. The next example shows how to use this function:
function notGlobal(){
	console.debug(this);
}

notGlobal.apply(obj,[1,2,'3',true]);

Conclusions

It is very important to understand the use of the variable "this" for the following chapters of this course. The context can be a very powerful tool if we know how to use it correctly, but it can be our worst headache if we haven't fully understand its concept.

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?

1Comentario

Instructor del curso

Crysfel3

Autor: Crysfel Villa

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

Descarga Código Fuente

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.