Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Is the next function (which actually works) bad in term of best practices?

The IDE is warning me about

'Potentially invalid usage of 'this'. Checks for Javascript 'this' to be in the same closure or outer 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 a checkbox with ID select-all, it marks all the other as selected.

like image 684
JorgeeFG Avatar asked Oct 10 '13 13:10

JorgeeFG


2 Answers

Most probably it happens because your IDE doesn't know what object this refers to in the functions you use, hence giving you a hint that this might refer to window object or another 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);
});
like image 171
VisioN Avatar answered Nov 03 '22 20:11

VisioN


@Jorge it has to do with the scope of closures in javascript and the usage of this.

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

I haven't read it completely but it sums it pretty nicely.

like image 38
gmaliar Avatar answered Nov 03 '22 20:11

gmaliar