猿问

Javascript - 箭头在事件处理程序中起作用吗?

Javascript - 箭头在事件处理程序中起作用吗?

我是ES6的新手,并且无法完成这项工作:

$(this) 单击时返回undefined?

dom.videoLinks.click((e) => {
            e.preventDefault();
            console.log($(this));
            var self = $(this),
                url = self.attr(configuration.attribute);

            eventHandlers.showVideo(url);

            // Deactivate any active video thumbs
            dom.videoLinks.filter('.video-selected').removeClass('video-selected');

            // Activate selected video thumb
            self.addClass('video-selected');
        });

但是,如果我改变它所以不是像这样的箭头函数,它按预期工作?:

dom.videoLinks.click(function(e) {
            e.preventDefault();
            console.log(this);
            console.log($(this));
            var self = e.this,
                url = self.attr(configuration.attribute);

            eventHandlers.showVideo(url);

            // Deactivate any active video thumbs
            dom.videoLinks.filter('.video-selected').removeClass('video-selected');

            // Activate selected video thumb
            self.addClass('video-selected');
        });

那么如果我在回调中使用箭头函数,我该怎么做呢?


潇潇雨雨
浏览 421回答 3
3回答

慕神8447489

你不会。更改值this是使用箭头功能的主要要点。如果你不想这样做那么箭头功能是错误的工具。
随时随地看视频慕课网APP
我要回答