gpt4 book ai didi

javascript - 通过 addEventListener 传递它

转载 作者:行者123 更新时间:2023-12-01 01:05:56 24 4
gpt4 key购买 nike

我有一个之前可以运行的函数;但我现在必须使用 setTimeout 让它等待。我以为我可以添加一个箭头函数作为 eventListener 的回调,并且仍然能够将 this 作为上下文的按钮传递,但我收到了错误。

button.addEventListener("click", () => {
setTimeout(checkAndRespond,1500);
});

//This is the line that throws the error
checkAndRespond = async function () {
...
const row = this.parentElement.parentElement;
...
}

我该如何将 this 传递到内部函数中?
setTimeout 上下文是否作为 this 传入 checkAndRespond?
关于箭头函数的工作原理,我有什么不明白的地方吗?

最佳答案

How am I supposed to pass this into the inner function?

哪个这个?箭头函数采用其父函数的上下文 (this),在本例中是全局范围,并且 this 指向 window。如果您想在特定上下文中动态调用函数(这就是 addEventListener 的作用),您必须使用常规函数

Is the setTimeout context being passed in as this to checkAndRespond?

没有。您必须手动.bind上下文:

 button.addEventListener("click", function() { // <- now we can work with this here
setTimeout(checkAndRespond.bind(this), 1500); // <- and bind it
});

或者您使用如上所述的箭头函数行为,并将 this 作为参数传递:

 button.addEventListener("click", function() {
setTimeout(() => checkAndRespond(this), 1500);
});

async function checkAndRespond(button) {
//...
}

旁注:

您也可以只使用 button 而不是 this,但这可能太简单了。

checkAndRespond = 是一个未声明的 (!!) 变量,请务必声明它们!

关于javascript - 通过 addEventListener 传递它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55637596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com