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

185
Visualizações
What is "this" refer to in JavaScript?

I write a function to add listener to all elements match a specific selector, as below:

        //  Add event handler to all elements match a specific selector
        function addEventListenerToAll(selector, type, listener)
        {
            [].forEach.call(document.querySelectorAll(selector), function(element) {
                if (element) {
                    element.addEventListener(type, listener);
                }
            });
        }

Then I invoke the function as below:

  addEventListenerToAll(".myclass", "click", function () {
      var url = this.getAttribute('myurl');  // What is 'this' refers to?
  });

Then what is 'this' in this.getAttribute refers to?

Based on my test, it refers to one of the elements in the foreach loop. However, I check this document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this and it said in "Class context", 'this' in a non-static function refers to the current class object, otherwise, it defaults to the global object, in browser, it should be the window object.

So, as the listener function is not a class member function, it should refer to window instead?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Functions can be given a different this scope to what would be the default. You can do this yourself with the apply method. (Edit: as @pilchard pointed out below, this doesn't apply to arrow functions, which inherit the parent scope.) In event listeners, the this refers to the element the event listener was applied to (currentTarget).

Reference: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#the_value_of_this_within_the_handler

about 4 years ago · Juan Pablo Isaza 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