1

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?

  • 1
    This is what arrow functions are for and what makes them unique. They don't generate a `this` and `this` remains the one from the context in which it is called. From MDN: "An arrow function expression has a shorter syntax than a function expression and **does not have its own this, arguments, super, or new.target**. These function expressions are best suited for non-method functions, and they cannot be used as constructors." – somethinghere Apr 05 '18 at 09:22
  • Keep using `function`, because you don't need `this` to refer to the outer context here. You want it to be what jQuery forces it to be (the element). – Frank Modica Apr 05 '18 at 09:22
  • If for some reason in the future you need an arrow function and you also need the element, `event` gets passed into the function, so you can use `event.target`. – Frank Modica Apr 05 '18 at 09:26
  • Thanks @FrankModica, this solution is viable for my approach. I am not sure why my question has been marked duplicate. You have answered the question well, and this worked for me. I knew there was another solution, and using ES5 function deceleration is not a choice. There is always a work around. Thank god I have the knowledge otherwise I would blindly follow what others say and do. – Code Realistic Apr 06 '18 at 07:48

1 Answers1

4

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.

gillyhl
  • 475
  • 2
  • 7