“this” keyword behaves differently when using arrow functions with jQuery callbacks [duplicate]

南楼画角 提交于 2020-05-24 02:52:30

问题


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 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.



来源:https://stackoverflow.com/questions/49668644/this-keyword-behaves-differently-when-using-arrow-functions-with-jquery-callba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!