JavaScript: 如何将参数传递给最终将被删除的侦听器函数

JavaScript: How to pass arguments to a listener function that will eventually be removed

我正在尝试调用一个函数,该函数具有触发事件时所依赖的参数。但是,此函数不能是匿名的,因为将来会删除侦听器。

我试图为包装器使用函数表达式,并将对 this 的引用作为主要函数中的参数传递:

<div id="div">
  click
</div>
function main() {
  let foo = "foo";
  let bar = "bar";
  let wrapFunction = function(event) {
    goodFunction(event, foo, bar, this);
  }
  document.getElementById("div").addEventListener("click", wrapFunction);
}
function goodFunction(e, foo, bar, wrapFunction) {
  alert(foo);
  alert(bar);
  document.getElementById("div").removeEventListener("click", wrapFunction);
}
main();

document.getElementById("div").removeEventListener("click", wrapFunction); 行外,一切正常。这是我无法弄清楚的部分,将不胜感激。

与其将 this 传递给 wrapFunction 内部的 goodFunction(event, foo, bar, this) 调用,不如传递 wrapFunction 本身,因为它是在处理程序运行时定义的叫:

function main() {
  let foo = "foo";
  let bar = "bar";
  let wrapFunction = function(event) {

    /* wrapFunction is defined so pass it directly to goodFunction */
    goodFunction(event, foo, bar, wrapFunction);
  }
  document.getElementById("div").addEventListener("click", wrapFunction);
}

function goodFunction(e, foo, bar, wrapFunction) {
  alert(foo);
  alert(bar);
  document.getElementById("div").removeEventListener("click", wrapFunction);
}
main();
<div id="div">Click me</div>