Use arrow functions in jQuery plugin

2019-09-14 00:22发布

问题:

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.