问题
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
, ornew.target
.
See this article for more information.
来源:https://stackoverflow.com/questions/43704847/use-arrow-functions-in-jquery-plugin