24

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?

Pori
  • 696
  • 3
  • 7
  • 18
  • Try searching first, please. There are many duplicates. `this` is "dynamically bound" to the *receiver* of the function, or to the global object (e.g. `window`). –  Sep 18 '12 at 22:05
  • 7
    Hint: `
  • ` wraps `foo()` inside of an anonymous function, rather than calling `foo()` directly. – Jeremy J Starcher Sep 18 '12 at 22:07
  • Hint2: The meaning of *this*, is relative to where you use it. – Jay Sep 18 '12 at 22:19
  • 2
    You may find it to be more sensible if you remove the inline event handlers. – cjc343 Sep 18 '12 at 22:28