JSHint says “Argument types do not match parameters” for jQuery(this)
-
21-12-2019 - |
Question
It's all in the title.
It happens with jQuery(document) as well.
I don't understand what is wrong in the code.
Here's the excerpt:
var checkboxes = jQuery('.js-selected-items', self.$el);
checkboxes.each(
function (i) {
if (!jQuery(this).is(':disabled')) {
jQuery(this).prop('checked', true);
}
}
);
...
That warning is shown for all occurrences of jQuery(this).
The code works, of course, but I'd like to get rid of all JSHint warnings.
Solution
You just need to set a flag for JSHint to allow the use of this
outside of a constructor function:
checkboxes.each(function() {
/* jshint validthis: true */
jQuery(this)...
});
From the JSHint docs for the validthis
configuration option:
This option (
validthis
) suppresses warnings about possible strict violations when the code is running in strict mode and you use this in a non-constructor function. You should use this option—in a function scope only—when you are positive that your use of this is valid in the strict mode (for example, if you call your function using Function.call).Note: This option can be used only inside of a function scope. JSHint will fail with an error if you will try to set this option globally.
Under the hood, jQuery#each
invokes your callback using Function#call
passing the current element in the loop as the first argument to that function, making the validthis
flag for JSHint OK to use in this situation.
OTHER TIPS
The parameter of function of $.each()
is:
Type: Function( Integer index, Element element )
So use element
instead of this
will satisfy JSHint, or PHPStorm inspection in my case.
checkboxes.each(function (i, elm) {
if (!$(elm).is(':disabled')) {
$(elm).prop('checked', true);
}
});