Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!