Using 'this' inside anonymous, IDE: potentially invalid use

Is the following function (which really works) bad from a best practice point of view?

IDE warns me about

'Potentially incorrect use of' this'. Checks for Javascript 'this' in the same closure or external content.

$(document).on('change', '#select-all', function(){ if( this.checked ) { $(this).closest('table').find('input[name="row-id"]').each( function() { this.checked = true; // Here }) } else { $(this).closest('table').find('input[name="row-id"]').each( function() { this.checked = false; // Here }); } }); 

When I check the box with the identifier select-all , it marks all the others as selected.

+7
javascript
source share
2 answers

Most likely, this is because your IDE does not know which this object belongs to the functions you use, therefore it gives you a hint that this may refer to a window object or other context.

By the way, your code can be rewritten to:

 $(document).on("change", "#select-all", function() { $(this) .closest("table") .find("input[name='row-id']") .prop("checked", this.checked); }); 
+5
source share

@Jorge this is due to the volume of closures in javascript and the use of this .

For further reading, try the following: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

I did not read it completely, but he summarizes it quite nicely.

+2
source share

All Articles