Node.js EventEmitter错误
我在尝试继承时出错Node.js EventEmitter错误,node.js,restify,eventemitter,Node.js,Restify,Eventemitter,我在尝试继承时出错 /* Consumer.js */ var EventEmitter = require('events').EventEmitter; var util = require('util'); var Consumer = function() {}; Consumer.prototype = { // ... functions ... findById: function(id) { this.emit('done', this); } }; u
/* 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'"}
我几乎什么都试过了,但有几件事还是不行。您正在覆盖原型,而不是扩展原型。另外,在添加新方法之前,请移动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");
有几件事。您正在覆盖原型,而不是扩展原型。另外,在添加新方法之前,请移动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");
我只是注意到了继承问题,为什么要离开c.findById appart?只是为了可读性,它试图确保我理解您的代码。另外,为什么Consumer.prototype={}不能工作,但是Consumer.prototype.function是因为您执行“Consumer.prototype={}”您正在覆盖prototype rater,而不是向其添加新的属性/函数。我刚刚注意到继承问题,为什么您要离开c.findById appart?只是为了可读性,它试图确保我理解您的代码。另外,为什么Consumer.prototype={}无法工作,但Consumer.prototype.function是因为您这样做了“Consumer.prototype={}”您正在覆盖prototype rater,而不是向其添加新的属性/函数。