function Auth() {
console.log('Created!')
}
Auth.prototype.authenticate = function () {
// do stuff
this.emit('completed')
}
util.inherits(Auth, EventEmitter)
如何在其他函数中调用 Auth.emit('someEvent') ?例如:
function someOther () {
//do stuff
Auth.emit('event')
}
它抛出一个错误:
Auth.emit 不是一个函数
最佳答案
您需要创建一个实例。
var myAuthObj = new Auth();
myAuthObj.authenticate(...);
原型(prototype)上的方法是“实例”方法。它们可以在对象的实例上直接调用。
您也可以创建“静态”方法(以不同的方式,它们实际上只是分配给命名空间对象的普通函数),但它们不能使用 this
或您继承的对象,因为它们被放入仅当您使用 new
和构造函数实例化实际对象时才放置。
您还需要将 util.inherits()
移到原型(prototype)分配的前面。 util.inherits() 语句替换了原型(prototype),因此如果您之后执行此操作,则会清除刚刚分配给原型(prototype)的内容。并且,您也应该调用父对象的构造函数。
function Auth() {
EventEmitter.call(this);
console.log('Created!')
}
util.inherits(Auth, EventEmitter);
Auth.prototype.authenticate = function () {
// do stuff
this.emit('completed')
}
因此,需要解决三件事:
- 在将任何内容分配给
Auth.prototype
之前,先移动util.inherits()
。 - 将
EventEmitter.call(this)
添加到构造函数中以正确初始化基础对象 - 使用
new Auth()
构造 Auth 对象的实例,并调用该实例的方法。
关于javascript - Node.JS:事件发射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087898/