0

尝试继承 EvenEmitter 时出现错误

/* Consumer.js */
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var Consumer = function() {};

Consumer.prototype = {
  // ... functions ...
  findById: function(id) {
    this.emit('done', this);
  }
};

util.inherits(Consumer, EventEmitter);
module.exports = Consumer;

/* index.js */
var consumer = new Consumer();
consumer.on('done', function(result) {
  console.log(result);
}).findById("50ac3d1281abba5454000001");

/* ERROR CODE */
{"code":"InternalError","message":"Object [object Object] has no method 'findById'"}

我已经尝试了几乎所有方法,但仍然无法正常工作

4

1 回答 1

3

有几件事。您正在覆盖原型而不是扩展它。此外,在添加新方法之前移动 util.inherits() 调用:

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

var Consumer = function Consumer() {}

util.inherits(Consumer, EventEmitter);

Consumer.prototype.findById = function(id) {
    this.emit('done', this);
    console.log('found');
};

var c = new Consumer();
c.on('done', function(result) {
  console.log(result);
});

c.findById("50ac3d1281abba5454000001");
于 2013-01-03T15:35:08.457 回答