View Full Version : JavaScript events are really just function references?

11-13-2010, 10:01 PM
Hey all,

I was reading a book and guy says an event is just a function reference, so you can programmatically call it like a function :

if (myDOMNode.onclick)

Here's my thing with this. How does the javascript engine know what function reference that this function reference is pointing to?

For example, in the now defunct event model (meaning that now you typically use addeventlistener), you would have done this:

myDOMNode.onclick = myClickHandler;

So obviously, myClickHandler is just an identifier pointing to a function, because you wouldn't want to call the function directly: myClickHandler() - otherwise interpreter will read that and execute it before it even sees what's on the left side of assignment.

But how is javascript grabbing that myClickHandler and doing something with it if all onclick is is a function reference?

Let's say you have this:

document.getElementById("bla").onclick = function(e) { myClickHandler(e, “John Merlino”); };

what is javascript really doing with onclick and the anonymous function?

For example, it's not like we are passing the anonymous function as an argument of onclick:

document.getElementById("bla").onclick({ myClickHandler(e, “John Merlino”));

I'm sure there's not a built in method like this in the engine:

Thanks for response.

11-13-2010, 10:23 PM
Because that way of incorporating an event handler automatically includes the 'this' functionality of javascript. It's a much better method than the inline.


Old Pedant
11-14-2010, 01:19 AM
not true. Or at least half-true.

If you want to pass "this" to the anonymous function, you *must* do so yourself.


document.getElementById("bla").onclick = function(e) { myClickHandler(e, this, “John Merlino”); };

Now, having said that, it's really not necessary to pass this as you can always get the object that caused the event from the event object. But it's often more convenient to do so, as if you use the event object you have to write browser-sensitive code.


By the way, the first code example there is wrong:

if (myDOMNode.onclick)

It would normally be:

if (myDOMNode.onclick)

That is, you simulate the *event* and that invokes the function that is referenced by the event *handler*.

11-14-2010, 01:25 AM
I think you and the author meant that an event handler is a function reference.

The event itself is defined and supplied by the interface of the client (browser) and operating system.

Old Pedant
11-14-2010, 01:27 AM
Yes, well said, Hoo. And if you think of it that way, you won't make the mistake of trying to invoke the event handler by doing


11-20-2010, 02:13 AM
Thanks links were helpful.