I'm just trying to understand the logic behind this code:
window.onkeydown = function () {
handler(event);
};
function handler(event)
{
console.log(event.key); // this works!
}
Shouldn't the event handler be declared with the event argument included in the anonymous function? Like so:
window.onkeydown = function (event) {
handler(event);
};
I understand that browsers automatically pass the event to the handler, but still I find it weird that assigning an anonymous function without arguments still works. Is this a normal behaviour?
Why are event argument optional in anonymous functions in Javascript?
They aren't, cross-browser. Microsoft had a global event
that was set to the current event before calling handlers using their attachEvent
(and onxyz
) handlers. The DOM standard went another way: passing event
as an argument.
Chrome and some other browsers do both, so that Microsoft-specific code works on them. But not all browsers do. Firefox doesn't, for instance, unless you set a special preference in your user preferences ( details ).
The key takeaway is: Use modern event handling ( addEventListener
, etc.), which is supported in all browsers other than IE8 and earlier, and declare the event
parameter to the function:
window.addEventListener("keydown", handler);
// ...
function handler(event) {
// ...
}
or (the function name is optional, but useful in error call stacks):
window.addEventListener("keydown", function handler(event) {
// ...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.