new funcion()
creates a new object and calls funcion
setting that new object is the value of this
for the function. (so funcion
makes the role of constructor / allows you to manipulate this
). Also, new funcion()
returns that object so that you can use it later, which fulfills the role of instance of the object.
When you invoke funcion()
directly, the value of this
depends on the context. If the function is invoked from the global scope (eg direct from a tag <script>
), then this
carries the value of window
. It does not use the this
of the current context.
Example:
function funcion() {
console.log(this === window);
this.otraFuncion = function() {
console.log(this === window);
}
}
// invocas a funcion, this es window.
funcion(); // true
// this es un nuevo objeto creado para tal fin.
var instancia = new funcion(); // false
// this es window
window.otraFuncion(); // true
// this es la instancia
instancia.otraFuncion(); // false
Another thing to keep in mind is that the value of this
depends on who invokes the function and not where it is declared .
This is a concrete example: the setTimeout
function invokes the callback from the context of window
. Therefore the value of this within the callback is window
.
Example:
function funcion() {
console.log( this === window );
setTimeout(function() {
// Aqui se aprecia que this depende de quien invoca y no del lugar donde una funcion esta declarada.
console.log( this === window );
}, 0);
}
funcion(); // true true
new funcion(); // false true
Salu2.