最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Event emitter constructor - Stack Overflow

programmeradmin1浏览0评论

I'm trying to understand how objects bee event emitters. The documentation has something similar to the following code:

var EventEmitter = require('events').EventEmitter;

function Job(){
  EventEmitter.call(this);
}

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

> var j = new Job()
undefined
> j.emit('test')
TypeError: Object #<Job> has no method 'emit'

After setting the prototype via Job.prototype = new EventEmitter; seems to work as expected.

I'm trying to understand how objects bee event emitters. The documentation has something similar to the following code:

var EventEmitter = require('events').EventEmitter;

function Job(){
  EventEmitter.call(this);
}

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

> var j = new Job()
undefined
> j.emit('test')
TypeError: Object #<Job> has no method 'emit'

After setting the prototype via Job.prototype = new EventEmitter; seems to work as expected.

Share Improve this question asked Sep 16, 2015 at 21:29 Allyl IsocyanateAllyl Isocyanate 13.6k17 gold badges85 silver badges132 bronze badges 2
  • 1 The more important thing is what follows that, util.inherits(Job, EventEmitter);. Please check this – thefourtheye Commented Sep 16, 2015 at 21:31
  • blog.slaks/2013-09-03/traditional-inheritance-in-javascript – SLaks Commented Sep 16, 2015 at 21:34
Add a ment  | 

4 Answers 4

Reset to default 3

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

Yes, it's basically a super call that initialises the emitter instance. See also What is the difference between these two constructor patterns? for what it does.

After setting the prototype it seems to work as expected.

Indeed, you need to let your Jobs inherit from EventEmitter. However, you really should not use new here, but rather

Job.prototype = Object.create(EventEmitter.prototype);

Also have a look at Node.js - inheriting from EventEmitter.

This worked for me

let events = require('events');
let eventEmitter = new events.EventEmitter();

With ES6 (I use babel although its not necessary for most features with the latest Node) you can just do this:

import {EventEmitter} from 'events';

export class Job extends EventEmitter {
  constructor() {
    super();
  }
}

let job = new Job();

Below the Job definition you can inherit from EventEmitter as follows

util.inherits(Job, EventEmitter);

Job will bee an eventemitter as you want. Thats a good way of "extending" an "object"

发布评论

评论列表(0)

  1. 暂无评论