Tengo un programa como:
$(document).ready(function() { this.name = "John"; var someFunc = function() { return this.name; } }); Según tengo entendido, el valor de ' esto ' en someFunc es "ventana" ya que no está contenido en ningún objeto.
Mi pregunta es ¿por qué el valor de ' this ' es ' HtmlDocument ' en $(document).ready(function() { alert(this) } ?
Y dado que someFunc está bajo la función $(document).ready , ¿por qué su valor no puede ser ' HtmlDocument ' también? ¿Qué sucede exactamente detrás de escena que hace que el valor de esto sea diferente en diferentes casos?
La variable this tiene un concepto de alcance en JavaScript, su valor depende de dónde acceda a ella, trataría de explicar esto con un ejemplo, vea el siguiente fragmento de código:
$("#document").ready(function() { console.log("HERE 'this' references to its owner object \"HTMLDocument\""); console.log(this.toString()); jsFunction(); $("#test").jqueryFunction(); console.log("You could call jsFunction on window:"); window.jsFunction(); console.log("But you can't call jqueryFunction on window:"); try{ window.jqueryFunction(); }catch(err){console.log("error");} console.log("Neither you could call jsFunction on \"div test\":"); try{ $("#test").jsFunction(); }catch(err){console.log("error");} //Inner functions console.log("The same thing applies to inner functions"); var innerFunc = function(){ console.log(this.toString()); var moreInnerFunc = function(){ console.log(this.toString()); } moreInnerFunc(); } innerFunc(); (function(){ console.log("Immediately-Invoked Function Expression (IIFE)"); console.log(this.toString()); })(); var extDeclared = externallyDeclared; extDeclared(); $("#document").extDeclared(); }); function jsFunction(){ console.log("HERE 'this' references to its owner \"window\""); console.log(this.toString()); } (function( $ ){ $.fn.jqueryFunction = function() { console.log("HERE 'this' references to its owner \"div test\""); console.log($(this).prop("id")); }; })( jQuery ); function externallyDeclared(){ console.log("externallyDeclared may be window or its other owner"); console.log(this.toString()); } (function( $ ){ $.fn.extDeclared = externallyDeclared; })( jQuery ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test" /> Como puede ver, this siempre hace referencia a su objeto "propietario", por lo que cuando declara una función fuera de cualquier tipo de objeto, su propietario es el objeto window , de lo contrario, hace referencia al objeto donde se define la función.
En resumen:
function externallyDeclared(){ console.log("externallyDeclared may be window or its other owner"); console.log(this.toString()); } (function( $ ){ $.fn.extDeclared = externallyDeclared; })( jQuery ); $("document").ready(function(){ var extDeclared = externallyDeclared; extDeclared(); //<-- "no owner" - this=window $("#document").extDeclared(); //<-- "has an owner" - this=its owner });Espero haber sido claro, adiós.