我正在学习nodejs,出现了一些问题,emit()和on()不是一个函数..
这是我的emitter.js 文件
function Emitter(){
this.events = {};
}
Emitter.prototype.on = function(type, listener){
this.events[type]=this.events[type]||[];
this.events[type].push(listener);
}
Emitter.prototype.emit = function(type){
if (this.events[type]) {
this.events[type].forEach(function(listener){
listener();
});
}
}
这是我的 app.js 文件
//Emitter
var Emitter = require('./emitter');
Emitter.on('greet', function(){
console.log('a greeting occured!`');
});
console.log('hello');
Emitter.emit('greet');
这是错误
类型错误:Emitter.on 不是一个函数
当我实例化发射器时:
varemitter = new Emitter();
这是错误:
类型错误:发射器不是构造函数
然后,我使用以下文字语法导出模块:
module.exports= {emit: 发射}
仍然出现错误,new Emitter() is not a constructor
所以,我用这个导出它:
module.exports = Emitter;
而不是使用这种模式module.exports = {emit: Emitter}
,我仍然不知道为什么我不能用文字导出它,知道吗?
最佳答案
您已经创建了一个类。使用new Emitter()
创建它的实例。此外,您还必须导出和导入 Emitter
类:
// emitter.js
function Emitter(){
this.events = {};
}
Emitter.prototype.on = function(type, listener){
this.events[type]=this.events[type]||[];
this.events[type].push(listener);
}
Emitter.prototype.emit = function(type){
if (this.events[type]) {
this.events[type].forEach(function(listener){
listener();
});
}
}
// Export the Emitter class: module.exports = Emitter;
// app.js
// Import the emitter class: var Emitter = require('./emitter');
var emitter = new Emitter();
emitter.on('greet', function(){
console.log('a greeting occured!`');
});
console.log('hello');
emitter.emit('greet');
每当您将 new
运算符与构造函数一起使用时,都会创建一个新对象。该对象的原型(prototype)将是构造函数的 prototype
属性。然后,使用新对象调用构造函数(构造函数中的 this
就是新对象)。
关于javascript - emit() 和 on() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45275379/