Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda