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

huangapple go评论75阅读模式
英文:

Why are event argument optional in anonymous functions in Javascript?

问题

I understand. Here's the translated code:

我只是试图理解这段代码背后的逻辑:

    window.onkeydown = function () {
        handler(event);
    };
    function handler(event)
    {
        console.log(event.key); // 这个可以工作!
    }

事件处理程序不应该在匿名函数中包含事件参数吗?像这样:

    window.onkeydown = function (event) {
        handler(event);
    };

我明白浏览器会自动将事件传递给处理程序,但我仍然觉得在没有参数的匿名函数中分配它仍然能够工作很奇怪。这是正常行为吗?
英文:

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?

答案1

得分: 1

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

它们并不是在所有浏览器中都可选的。Microsoft 曾经有一个 全局 event,在调用处理程序之前,使用他们的 attachEvent(和 onxyz)处理程序将其设置为当前事件。DOM 标准采用了另一种方式:将 event 作为参数传递。

Chrome 和一些其他浏览器都支持两种方式,以便 Microsoft 特定的代码在其中正常工作。但并非所有浏览器都支持。例如,Firefox 不支持,除非在用户首选项中设置特殊偏好项(详情)。

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

window.addEventListener("keydown", handler);

// ...

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

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

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

> 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) {
    // ...
});

huangapple
  • 本文由 发表于 2020年1月6日 22:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定