具有匿名功能的事件监听器 [英] Event Listener with anonymous function

查看:90
本文介绍了具有匿名功能的事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它写在 MDN


如果要将参数传递给侦听器函数,则可以使用匿名函数。

If you want to pass parameters to the listener function, you may use an anonymous function.

经过一些试验,当我尝试使用这样的单参数函数(没有匿名函数)注册事件侦听器时,便发现

After some experimentation I figured out when I try to register an event listener with a one-parameter function like this (without an anonymous function)

target.addEventListener(type, doSomething(parameter));

即使没有发生事件,侦听器函数也会执行,但是当我将其包装在匿名函数

the listener function executes even when an event didn't happen, but when I wrap it up in an anonymous function

target.addEventListener(type, function () {doSomething(parameter);});

一切都按预期进行。

为什么这种行为会发生吗?我猜想它与闭包有某种联系。

Why does such behavior take place? I guess it is somehow connected with closures.

推荐答案

像这样定义处理程序函数时

When defining the handler function like so

target.addEventListener(type, doSomething(parameter));

您正在传递函数的返回值作为处理函数。例如,考虑以下函数:

You are passing the function's return value as handler. For example consider this function:

function doSomething(event) {
    return 'foo';
}

现在,在事件发生之前,该函数将立即执行,您基本上只是将其作为处理程序传递:

Now, the function gets executed immediatly, before the event has happened, and you are basically just passing this as handler:

target.addEventListener(type, 'foo');

那是行不通的。

第二个示例

target.addEventListener(type, function () {doSomething(parameter);});

正确地传递了一个函数作为引用,而没有在事件发生之前执行它。

correctly passes a function as reference, without having it executed before the event occurred.

这篇关于具有匿名功能的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆