In Google Closure Compiler I get the warning
WARNING – dangerous use of the global this object
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
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.
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?
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.See the Closure Compiler warning reference. The Closure Compiler gives this warning when you use
thiswithin a function that is not either annotated/** @constructor */or is within theprototypeof a class. The compiler assumes that you’ll never usethiswhen a function is called in the context of another object (which is what event callbacks do).Some places that you might have to change to make Closure Compiler stop complaining with this warning:
link.onclick = ...directly, because you have to mess withthisande || window.event. Instead, use jQuery to wrap the event handler, since jQuery’s event object hase.currentTarget.thiswithin ajQuery.each, replacethiswith the second parameter of your function. E.g.,jQuery.each([1, 2, 3], function(i, val) { ... val ... };.