首页 > 解决方案 > Why are event argument optional in anonymous functions in Javascript?

问题描述

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?

标签: javascriptbrowserdom-events

解决方案


为什么事件参数在 Javascript 的匿名函数中是可选的?

他们不是,跨浏览器。Microsoft 在使用其(和)处理程序调用处理程序之前将全局 event设置为当前事件。DOM 标准采用了另一种方式:作为参数传递。attachEventonxyzevent

Chrome 和其他一些浏览器两者兼而有之,因此 Microsoft 特定的代码可以在它们上面运行。但并非所有浏览器都这样做。例如,除非您在用户首选项(详细信息)中设置特殊首选项,否则 Firefox 不会。

关键要点是:使用除 IE8 及更早版本之外的所有浏览器都支持的现代事件处理(addEventListener等),并为event函数声明参数:

window.addEventListener("keydown", handler);

// ...

function handler(event) {
    // ...
}

或(函数名是可选的,但在错误调用堆栈中很有用):

window.addEventListener("keydown", function handler(event) {
    // ...
});

推荐阅读