Search code examples
javascriptjqueryclassoopclass-method

Get class property from jquery callback


I have a class:

class MyClass{
    #arr= [];


    constructor(){
        $("body").on("click", ".myClass", function(e){
           //here, i need to access this.#arr, but unfortunatelly "this" no longer represents MyClass.
        }
    }
}

How would I go about doing this? Thanks in advance!


Solution

  • Use an arrow function instead to preserve the this value, after which you can use e.target to get the element that was clicked.

    $("body").on("click", ".myClass", e=>{
    
    });