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

115
Views
Access property of an object from jquery function within the object (JavaScript/jQuery)

I have the following class:

class Traffic {
    constructor(name) {
        this.name = name;
    }
    setEventListeners() {
        $("#btn").on('click', function() {
            $(this).text(name);
        }
    }
}

When clicking on the <button id="btn"></button>This throws the error: name is undefined. This makes sense to me as I would normally use this.name to access the object's properties. However, because I am inside jQuery, now this refers to the jQuery object.

How can I access the name property of the Traffic object?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can just declare a new variable outside the function where this still points to the class instance.

setEventListeners() {
    const name = this.name;
    $("#btn").on('click', function() {
        $(this).text(name);
    }
}
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!