-9
<td><a href="javascript:alert(this)">dele</a></td>
<li onclick ="alert(this)"></li>

here, why the "this" of "a" is window, the "this" of "li" is HTMLLiElement?

  • this is a moving target https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this – Luca Aug 03 '15 at 12:46

3 Answers3

6

When event handlers are invoked, the context is the target of the event. But processing the href attribute is not an event handler, there is no target there, so the context is window.

Use:

<a href="#" onclick="alert(this)">dele</a>
Barmar
  • 596,455
  • 48
  • 393
  • 495
1

this in your use cases is determined by how you are invoking alert. In the first instance, you are executing a statement in the global context by using href. In the second instance, you have attached an event handler to the li element, meaning the execution context is that element.

sdgluck
  • 18,456
  • 4
  • 56
  • 83
1

When <td><a href="javascript:alert(this)">dele</a></td> is clicked, the alert(this) does NOT run on the current page. It runs separately as an anonymous function with NO context, hence a Window.

BUT, in case of <li onclick ="alert(this)"></li>, the alert(this) run on the same page with the context of <li> which is an HtmlLiElement.

Shrinivas Shukla
  • 3,885
  • 2
  • 17
  • 30