I've come across a head scratching issue with my JavaScript application.
If I write an element like this:
<li onClick="alert(this.tagName)"></li>
I get "LI."
However if I do this:
<li onClick="foo()"></li>
Where "foo()" is:
function foo(){ alert(this.tagName); }
I get "undefined."
I am away how "this" is supposed to work in regards to attached functions. But, I am baffled because "this" is not picking up the element, but apparently defaulting to "window." I can't figure out why this is happening.
Does anyone have an explanation?
this
is "dynamically bound" to the receiver of the function, or to the global object (e.g.window
).<li onClick="foo()"></li>
wrapsfoo()
inside of an anonymous function, rather than callingfoo()
directly.