Node.js-从EventEmitter继承 [英] Node.js - inheriting from EventEmitter
问题描述
我在许多Node.js库中看到了这种模式:
I see this pattern in quite a few Node.js libraries:
Master.prototype.__proto__ = EventEmitter.prototype;
(来源此处)
有人可以举个例子给我解释一下,为什么这是一种常见的模式,什么时候方便吗?
Can someone please explain to me with an example, why this is such a common pattern and when it's handy?
推荐答案
如该代码上面的注释所述,它将使Master
从EventEmitter.prototype
继承,因此您可以使用该'class'的实例进行发射和听事件.
As the comment above that code says, it will make Master
inherit from EventEmitter.prototype
, so you can use instances of that 'class' to emit and listen to events.
例如,您现在可以执行以下操作:
For example you could now do:
masterInstance = new Master();
masterInstance.on('an_event', function () {
console.log('an event has happened');
});
// trigger the event
masterInstance.emit('an_event');
更新:正如许多用户指出的那样,在Node中执行此操作的标准"方法是使用"util.inherits":
Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':
var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);
第二次更新:随着ES6类的出现,建议立即扩展EventEmitter
类:
2nd Update: with ES6 classes upon us, it is recommended to extend the EventEmitter
class now:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
请参见 https://nodejs.org/api/events.html#events_events
这篇关于Node.js-从EventEmitter继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!