我正在学习nodejs并出现了一些问题,那就是embed()和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');





这是错误
TypeError: Emitter.on is not a function

当我实例化发射器时:
var emitter = new Emitter();

这是错误:
TypeError: Emitter is not a constructor
然后,我使用以下文字语法导出模块:
module.exports= {emit: Emit}
错误仍然出现,the 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属性。然后,用新对象调用构造函数(构造函数中的this是新对象)。

10-08 00:14