Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript assign context to this of event handlers?

After reading related questions #1 , #2 I still haven't found an answer to the following question:

Javascript can set context (i.e. set this) with: bind , call and apply.

But when I'm write an event handler:

document.getElementById('myInput').onclick = function ()
                                                   {
                                                      alert(this.value)
                                                   }

Who/What actually attaches this to the object itself ?

P.S. When using jQuery's :

  $("#myInput").bind(function (){...})

there is an internal implementation of (bind, call or apply)

So when I am not using jQuery, who is doing it?

like image 356
Royi Namir Avatar asked Oct 04 '12 07:10

Royi Namir


2 Answers

Why, the DOM/JavaScript of course, it's supposed to work that way by W3C.

Event handlers are invoked in the context of a particular object (the current event target) and are provided with the event object itself.

Source

How exactly that happens, we don't know. It's an implementation detail.

All we know is, that the semantics as defined by the W3C are achieved in some way, but which part of the browser does that and and how, that is left up to the browser developers, and they can implement it as they see fit.

like image 179
phant0m Avatar answered Nov 15 '22 21:11

phant0m


To sum up all the discussions:

  • In general it is JavaScript that binds this to o inside a function call, when o.x() is called.
  • However, there are some alternative methods of calling functions (like f.apply() and f.call()) that change this behaviour.
  • onclick is a special case, and the method used to invoke it is unknown and depends on the DOM implementation.
like image 28
wroniasty Avatar answered Nov 15 '22 22:11

wroniasty