gpt4 book ai didi

javascript - 在扩展 EventEmitter 的 ES6 类定义中设置事件监听器

转载 作者:IT老高 更新时间:2023-10-28 23:25:24 24 4
gpt4 key购买 nike

我想要一些预定义的自定义监听器,这些监听器已经用类的定义 定义(如 'newListner' 事件中的构建)。所以我不想只在构造函数中绑定(bind)它们,因为它将在该类的每个新实例上执行。

如何做到这一点?修改原型(prototype)?有可能吗?

到目前为止我所拥有的:

class Cat extends EventEmitter {
// just added for demonstration, I don't want this!
constructor() {
super();
// does fire
this.on('wave', function() { console.log('constructor wave'); });
}
}
// compiles but does not fire
Cat.prototype.on('wave', function() { console.log('prototype wave'); });

var cat = new Cat();
cat.emit('wave');

最佳答案

您无法避免为每个实例分别注册监听器,而这样做的自然位置是在构造函数中1、2。但是,您可以避免创建新的监听器函数:

class Cat extends EventEmitter {
constructor() {
super();
this.on('wave', this.onWave);
}
onWave() {
console.log('prototype wave');
}
}

var cat = new Cat();
cat.emit('wave');

1:还有其他方法,例如 ._events 的 getter。你可以用它做各种花哨的东西,包括“默认”监听器的原型(prototype)继承,但这些都过于复杂并且很快就会让你忘记。只需在构造函数中添加一些通用代码,您也可以做一些花哨的事情——而且更简洁。
2:你也可以重写(特化)EventEmitters 的 init 方法,但归根结底是完全一样的。

关于javascript - 在扩展 EventEmitter 的 ES6 类定义中设置事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35796828/

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