刚学 js,不太熟悉回调函数,想问下这个代码会出问题吗

2021-08-03 22:21:32 +08:00
 zxCoder
function init(fn){
    document.onkeydown=(e)=>{
        if(e.key==="Enter"){
            fn(true);
        }else if(e.key==="Escape"){
            fn(false);
        }
    }
}

let fn=(arg)=>{
    if(arg){
        console.log("enter");
    }else{
        console.log("esc");
        init(fn);
    }
}

init(fn)

想监听 enter 和 esc 键,实现一个类似前进和后退的动作,不知道这个代码会出问题吗,一开始以为是无限递归,但是跑起来又好像没问题

1361 次点击
所在节点    问与答
12 条回复
3dwelcome
2021-08-03 22:39:56 +08:00
不知道为什么要函数套娃,好像没什么实际意义,单纯为了测试?
zxCoder
2021-08-03 22:52:24 +08:00
@3dwelcome 因为写着写着就需要这样子。。。。把业务相关的拿掉就是这个结构了。。。我也觉得怪怪的
xiangyuecn
2021-08-03 23:19:09 +08:00
很正常不过的代码了,原汁原味的 js

函数赋值了一下而已,并没有调用
wunonglin
2021-08-03 23:50:23 +08:00
```
function init() {
document.onkeydown = (e) => {
switch (e.key) {
case 'Enter':
isEnter()
break;
case 'Escape':
isEscape()
break;
}
}
}

function isEnter() {
//
}

function isEscape() {
//
}

init()
```

这样每个按键的 func 各做各的不就行咯。
wenzichel
2021-08-04 00:12:16 +08:00
点击 esc 是会再次执行 init 方法,但只是 onkeydown 方法再次被重新定义而已。

init 中传入 fn 方法也是可以的,这 fn 就是一个回调函数,然后执行 fn 这个函数。
emonc
2021-08-04 00:43:26 +08:00
可读性好差😪
Puteulanus
2021-08-04 01:32:43 +08:00
document.addEventListener('keydown', console.log)
考虑下 Listener 不
learningman
2021-08-04 02:02:58 +08:00
可以是可以,好丑
raaaaaar
2021-08-04 08:35:54 +08:00
wenzichel
2021-08-04 10:44:21 +08:00
@Puteulanus 你这种写法,多次执行时,会造成重复监听!
Puteulanus
2021-08-04 11:04:46 +08:00
@wenzichel 先不说为什么要多次执行。。

> getEventListeners(document)
< {click: Array(1), DOMContentLoaded: Array(1), mouseup: Array(1)}

> document.addEventListener('keydown', console.log)
< undefined

> document.addEventListener('keydown', console.log)
< undefined

> getEventListeners(document)
< {keydown: Array(1), click: Array(1), DOMContentLoaded: Array(1), mouseup: Array(1)}

不用匿名函数,你确定会重复监听吗
看看 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#multiple_identical_event_listeners
wenzichel
2021-08-04 14:09:05 +08:00
@Puteulanus 哦,么事了,我是用匿名函数来注册的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/793479

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX