在匿名IDE中使用'this':可能无效的使用

Jor*_*eFG 7 javascript

在最佳实践方面,下一个功能(实际上是否有效)是不是很糟糕?

IDE警告我

''这个'的潜在无效用法.检查Javascript'this'是否在同一个闭包或外部内容中.

$(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
      });
    }
  });
Run Code Online (Sandbox Code Playgroud)

当我选中带有ID的复选框时select-all,它会将所有其他选项标记为已选中.

Vis*_*ioN 6

最有可能发生这种情况是因为您的IDE不知道this您使用的函数中引用了什么对象,因此为您提供了this可能引用window对象或其他上下文的提示.

顺便说一句,您的代码可以重写为:

$(document).on("change", "#select-all", function() {
    $(this)
      .closest("table")
      .find("input[name='row-id']")
      .prop("checked", this.checked);
});
Run Code Online (Sandbox Code Playgroud)