1

While looking back over some JS I'd written in the past, I noticed that I was trying to access event.keyCode in an event handler, but my function's only parameter was e, not event. So, while I would expect to get a "Uncaught ReferenceError: event is not defined", I instead found that my script works as expected (at least in Chrome).

document.body.addEventListener('keyup', function(e) {
    if (event.keyCode === 13) {
        // ...
    }
});

In fact, if I place a console.log(e === event) in that handler, I get true. After a little testing (in a JS Bin) it seems like this must apply to every such event, making event another sort of "sly" local variable like arguments that appears in a function without asking for it in a parameter.

This makes me wonder:

  1. Are these the only two "sly" local variables?
  2. Is this behavior with event in Chrome consistent with other browsers & JS environments?
Web_Designer
  • 72,308
  • 93
  • 206
  • 262

1 Answers1

2

Depending on the browser, there is a global event variable that refers to the currently fired event.

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Oh, I just assumed it was local. Hmm. – Web_Designer Apr 15 '17 at 02:04
  • @Web_Designer iirc, there was once a time where event handlers did `var event = event || window.event` to make sure they got a handle on the event, global or local. I think it was IE's `attachEvent` that didn't pass in `event` as handler argument. – Joseph Apr 15 '17 at 02:05
  • Now that you mention it, I have seen that before, but never used it. How would that have helped to get a handle on the event? Was the object once not passed as an argument to event handlers? – Web_Designer Apr 15 '17 at 02:08