In javascript the reserved word or operator this
refers to the current object, I can can be modified (see use of Function.prototype.bind()
) for other purposes.
It serves, as a general rule, to differentiate between variables of global and local scope, accessing that of the object.
I'll give you an example to show you the difference.
var variable = 'Esta es una variable global';
var objeto = {
variable: 'Esta es una variable de objeto',
prueba: 'Esto no debería funcionar sin "this"',
Constructor: function() {
var variable = 'Esta es una variable local';
/* Primera ronda de pruebas */
console.log('window.variable: ' + window.variable);
console.log('this.variable: ' + this.variable);
console.log('variable: ' + variable);
/* Segunda ronda de pruebas */
try {
console.log('prueba: ' + prueba);
} catch(e) {
console.log(e.message);
}
console.log('this.prueba: ' + this.prueba);
}
};
objeto.Constructor();
As you may have checked in the first round of tests, the global variables are defined in the scope of window
, the local ones are accessed directly and in the case of the scope of the object, this
must be used to access them.
In the second round of tests, an exception prueba is not defined
is generated when we try to access an object variable without using this
.
Depending on the strict mode or not and several areas its behavior is different, but as a general rule its use is widely extended in the scope of an object, but in the global context , outside of any function, this
refers to the global object (whether in strict mode or not).