警告 - 危险使用全局此对象

Bry*_*eld 8 javascript google-closure google-closure-compiler

在Google Closure Compiler中,我收到了警告

警告 - 危险使用全局此对象

这是一个例子.错误行和偏移量指的是单词的开头this

function aToggle() {
  if(shown)
    toggle.show()
  else
    toggle.hide()
  $(this).text(shown ? 'Click to hide' : 'Click to show')
  shown = !shown
}
link.onclick = aToggle
Run Code Online (Sandbox Code Playgroud)

我只是将它改为匿名方法,但我aToggle在文件的其他地方重新使用,所以需要命名.

我可以标记aToggle/**@constructor*/- 但它不是构造函数.是否有另一个注释我可以用来消除这个警告,或者我是否在将其标记为构造函数或者出现一堆无用的警告之间?

yon*_*ran 13

编辑:我一直在阅读Closure:The Definitive Guide,我刚刚意识到您可以在事件处理程序之前添加/** @this {Element} */注释,以使Closure Compiler停止抱怨.

请参阅Closure Compiler警告参考.当您this在未注释/** @constructor */或属于prototype类的函数中使用时,Closure Compiler会发出此警告.编译器假定您永远不会this在另一个对象的上下文中调用函数时使用(这是事件回调的作用).

您可能需要更改的某些地方使Closure Compiler停止抱怨此警告:

  • 不要使用link.onclick = ...直接的,因为你要惹thise || window.event.相反,使用jQuery来包装事件处理程序,因为jQuery的事件对象具有e.currentTarget.
  • 如果您this在a中使用jQuery.each,请替换this为函数的第二个参数.例如,jQuery.each([1, 2, 3], function(i, val) { ... val ... };.