通过addEventListener传递此信息

问题描述 投票:0回答:1

我有一个以前工作的功能;但是我必须让它等待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? 有什么我不理解箭头功能如何工作?

javascript event-handling this
1个回答
2
投票

我该如何将其传递给内部函数?

哪个this?箭头函数采用其父函数的上下文(this),在这种情况下是全局范围,并且this指向window。如果你想在某个上下文中动态调用一个函数(这就是addEventListeners所做的那样),你必须使用常规的function

是否将setTimeout上下文传递给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 =是一个未声明的(!!)变量,总是声明它们!

© www.soinside.com 2019 - 2024. All rights reserved.