Search code examples
javascriptarrow-functions

"this" keyword behaves differently when using arrow functions with jQuery callbacks


I have a table with multiple rows, and on each row, there is an edit and delete button.

In short, when an edit button is triggered with class .edit, a form pops-up. Along with the class name, I have also included a unique id like id="edit-32", where the number changes depending on what row the user clicks on.

The problem I am trying to solve is to capture the id attributes number after the dash. Previously, in ES5, I have simply used this keywoard to target the current element being clicked. But in ES6, this keywoard is refereing to the class environment.

ES5 approach (returns unique ID)

    //  Open edit form
    $('.edit').click(function(){

        // Return id attribute
        const id = $(this).attr('id'); 

        // print to console
        console.log(id); 
    }); 

ES6 approach (Returns undefined)

    //  Open edit form
    $('.edit').click(() => {

        // Return id attribute
        const id = $(this).attr('id'); 

        // print to console
        console.log(id); 
    });

Is there a way I can make arrow functions work with similar approach to ES5?


Solution

  • this in normal functions resolves to the object that calls the function, so in this case, this is the element that is clicked on.

    this in arrow functions does not define its own this, instead the this value of the enclosing execution context is used.

    It won't work with arrow functions in this case. You'll have to stick to bog standard functions.