Javascript - arrow functions this in event handler?

前端 未结 4 1174
难免孤独
难免孤独 2020-11-22 16:54

I\'m new to ES6, and can\'t quite get this to work:

$(this) returns undefined on click?

dom.videoLinks.click((e) => {
            e.         


        
4条回答
  •  一整个雨季
    2020-11-22 17:26

    arrow functions and this selector?

    Arrow functions retain this from enclosing context. Eg.

    obj.method = function(){
        console.log(this);
        $('a').click(e=>{
                console.log(this);
        })
    };
    obj.method(); // logs obj
    $('a').click(); // logs obj
    

    So how would I go about it if I use an arrow function in the callback?

    You already can - to access event target you can use something like $(e.target), but beware of bubbling. So I recommend to use normal functions instead as callbacks.

提交回复
热议问题