0

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?

1 Answers1

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);
    }
}
skara9
  • 4,042
  • 1
  • 6
  • 21