Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
the value of 'this' inside a function

I have a program as :

$(document).ready(function() {

   this.name = "John";
   var someFunc = function()
   {
     return this.name;
   }
});

From my understanding , the value of 'this' in someFunc is "window" since it is not contained in any object.

My question is why is the value of 'this' is 'HtmlDocument' in $(document).ready(function() { alert(this) }?

And since someFunc is under $(document).ready function why cant its value not be 'HtmlDocument' as well ? Whats exactly happening behind the scene which is causing the value of this to be different in different cases?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The variable this has a concept of scope in JavaScript, its value depends on where you're accessing to it, I'd try to explain this with an example, see following code snippet:

$("#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" />

As you can see, this references always to its "owner" object, so when you declare a function outside any kind of object, its owner is the window object, otherwise it references to the object where the function is defined.

In summary:

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
});

I hope I was clear, bye.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda