Use arrow functions in jQuery plugin

无人久伴 提交于 2020-01-25 20:58:46

问题


I am writing a jQuery plugin. But it doesn't seem to work when I use arrow function to extend jQuery.

This works :

$.fn.extend({
    func: function (params) {
        var ob = $(this);
        var selector = $(this).selector;
        var defaults = {

        };

        params = $.extend(defaults, params);

        generate(ob, selector, params);
    }
});

But when I try to use arrow function, it returns me the window object :

$.fn.extend({
    func: (params) => {
        var ob = $(this); // returns window object
        var selector = $(this).selector;
        var defaults = {

        };

        params = $.extend(defaults, params);

        generate(ob, selector, params);
    }
});

I've also tried using this.currentTarget but it returns undefined.

Can someone please tell me what I'm doing wrong ??


回答1:


It's because different rules apply to arrow functions when it comes to binding this.

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

See this article for more information.



来源:https://stackoverflow.com/questions/43704847/use-arrow-functions-in-jquery-plugin

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