0

I can't quite get understand of this simple example:

<button onclick='clickHandler(this)'>test</button>

function clickHandler(el){
var a = this;

}

When clicking the button, el is mapped to HTML event listener. But, a=this called inside function gives me global window object. Why is this inside function body not a HTML event listener (in this case it's button).

FrenkyB
  • 5,161
  • 8
  • 54
  • 91
  • Because when a function is invoked without being a property of an object, the global `this` (or `undefined`) is the `this` value inside the function. If it were `obj.clickHandler()` then the `this` would be `obj`. Still, best to always avoid inline handlers – CertainPerformance Nov 21 '19 at 04:43
  • 1
    I've read the question that you posted and I quite well understand meaning of this. But only this example is not quite clear to me. This as attribute in the function it's not the same as this in the function body. – FrenkyB Nov 21 '19 at 04:46
  • 1
    Because a `this` value is never inherited from its caller (unless the caller does so explicitly like with `.call`) – CertainPerformance Nov 21 '19 at 04:53
  • @CertainPerformance and then you have EventTarget.addEventListener("evt", fn) and `dispatchEvent(evt)` which will *implictely* call `fn`... Here it's more that the attribute value is converted to an anonymous wrapper function **which** will be the handler. So the call to `clickHandler` is made from the global context, – Kaiido Nov 21 '19 at 04:55
  • @CertainPerformance - why it's best to avoid inline handlers? – FrenkyB Nov 21 '19 at 05:41
  • - Global pollution (generally, everything referenced in an inline handler must be global or the element itself) - String escaping issues (since they're being written in HTML markup) - Very strange scoping behavior (both the element and the document are `with`ed inside an inline handler, which is horrendous) - No way to reference a closure's variable when creating an inline handler, etc... best to never use them, attach the listener properly using Javascript instead – CertainPerformance Nov 21 '19 at 05:45

0 Answers0