我有这个内联的js代码.
let btn = document.querySelector("button");
btn.addEventListener("click", foo, { once: true });
function foo() {
btn.addEventListener("click", bar, { once: true });
console.log("Foo called");
console.trace();
}
function bar() {
btn.addEventListener("click", buz, { once: true });
console.log("Bar called");
console.trace();
}
function buz() {
btn.addEventListener("click", foo, { once: true });
console.log("Buz called");
console.trace();
}
<button>Click</button>
我收到的结果有点难以理解.点击几下按钮后,它会显示如下所示.
Foo called index.html:11:17
foo file:///.../index.html:12
(Async: EventListener.handleEvent)
Bar called index.html:16:17
bar file:///.../index.html:17
(Async: EventListener.handleEvent)
foo file:///.../index.html:10
(Async: EventListener.handleEvent)
Buz called index.html:21:17
buz file:///.../index.html:22
(Async: EventListener.handleEvent)
bar file:///.../index.html:15
(Async: EventListener.handleEvent)
foo file:///.../index.html:10
(Async: EventListener.handleEvent)
正如您所看到的,在"名为index.html:16:17的Bar"行,似乎有两个堆栈帧.在"Buz Call"处有三个堆栈帧.所以我的问题是为什么会发生这种情况?
我预计它会产生这样的东西.
Foo called index.html:11:17
foo file:///.../index.html:12
(Async: EventListener.handleEvent)
Bar called index.html:16:17
bar file:///.../index.html:17
(Async: EventListener.handleEvent)
Buz called index.html:21:17
buz file:///.../index.html:22
(Async: EventListener.handleEvent)