它写在 MDN 上那个
If you want to pass parameters to the listener function, you may use an anonymous function.
经过一些实验后,我发现当我尝试使用这样的单参数函数(没有匿名函数)注册事件监听器时
target.addEventListener(type, doSomething(parameter));
即使事件没有发生,监听器函数也会执行,但是当我将其包装在匿名函数中时
target.addEventListener(type, function () {doSomething(parameter);});
一切都按预期进行。
为什么会发生这样的行为?我猜它与闭包有某种联系。
最佳答案
像这样定义处理函数时
target.addEventListener(type, doSomething(parameter));
您将函数的返回值作为处理程序传递。例如考虑这个功能:
function doSomething(event) {
return 'foo';
}
现在,该函数在事件发生之前立即执行,您基本上只是将其作为处理程序传递:
target.addEventListener(type, 'foo');
那行不通。
第二个例子
target.addEventListener(type, function () {doSomething(parameter);});
正确传递一个函数作为引用,而不是在事件发生之前执行它。
关于javascript - 具有匿名函数的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35509877/