警告-危险使用全局this对象 [英] WARNING - dangerous use of the global this object
问题描述
在Google Closure编译器中,我得到警告
In Google Closure Compiler I get the warning
警告-危险使用全局this对象
WARNING - dangerous use of the global this object
这里是一个例子.错误行和偏移量是指单词this
Here is an example. The error line and offset refers to the beginning of the word this
function aToggle() {
if(shown)
toggle.show()
else
toggle.hide()
$(this).text(shown ? 'Click to hide' : 'Click to show')
shown = !shown
}
link.onclick = aToggle
我只是将其更改为匿名方法,但是我在文件的其他位置重复使用aToggle
,因此需要对其进行命名.
I would just change it to an anonymous method, but I am re-using aToggle
elsewhere in the file, so it needs to be named.
我可以将aToggle
标记为/**@constructor*/
,但是它不是构造函数.我是否可以使用其他注释来消除此警告,还是在将其标记为构造函数还是出现一堆无用的警告之间卡住了?
I could mark aToggle
as /**@constructor*/
-- but it is not a constructor. Is there another annotation I can use to eliminate this warning, or am I stuck between marking it as constructor or having a bunch of useless warnings show up?
推荐答案
编辑:我一直在阅读《封闭:权威指南》,而我只是意识到,您可以简单地添加 /** @this {Element} */
批注在事件处理程序之前Closure编译器停止抱怨.
Edit: I've been reading Closure: The Definitive Guide, and I just realized that you can simply add the /** @this {Element} */
annotation before your event handler to make Closure Compiler stop complaining.
请参见 Closure Compiler警告参考.当您在未注释/** @constructor */
或类的prototype
中的函数中使用this
时,Closure Compiler会发出此警告.编译器假定在另一个对象的上下文中调用函数时,您永远不会使用this
(这是事件回调的作用).
See the Closure Compiler warning reference. The Closure Compiler gives this warning when you use this
within a function that is not either annotated /** @constructor */
or is within the prototype
of a class. The compiler assumes that you'll never use this
when a function is called in the context of another object (which is what event callbacks do).
您可能需要更改某些地方以使Closure Compiler停止抱怨此警告:
Some places that you might have to change to make Closure Compiler stop complaining with this warning:
- 请勿直接使用
link.onclick = ...
,因为您必须弄乱this
和e || window.event
.相反,请使用jQuery包装事件处理程序,因为 jQuery的事件对象具有e.currentTarget
. - 如果要在
jQuery.each
中使用this
,请将this
替换为函数的第二个参数.例如jQuery.each([1, 2, 3], function(i, val) { ... val ... };
.
- Don't use
link.onclick = ...
directly, because you have to mess withthis
ande || window.event
. Instead, use jQuery to wrap the event handler, since jQuery's event object hase.currentTarget
. - If you're using
this
within ajQuery.each
, replacethis
with the second parameter of your function. E.g.,jQuery.each([1, 2, 3], function(i, val) { ... val ... };
.
这篇关于警告-危险使用全局this对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!