Node.js EventEmitter继承报错:TypeError: this.on is not a function 问题咨询
解决TypeError: this.on is not a function的问题
嘿,这个问题我碰到过好多次啦!你已经做了一半正确的事——用EventEmitter.call(this)继承了EventEmitter的实例属性,但没打通原型链,导致你的自定义Emitter实例访问不到on、emit这些定义在EventEmitter原型上的方法,所以才会报this.on is not a function的错。
问题根源
EventEmitter的核心方法(比如on、emit)都存在于EventEmitter.prototype上,而你只通过call实现了实例属性的继承,原型链没连接起来,你的myEmitter根本找不到这些原型方法。
两种修正方案
方案1:ES5构造函数手动处理原型链
const EventEmitter = require('events') const Emitter = function () { EventEmitter.call(this) // 继承EventEmitter的实例属性 this.on('event', value => { console.log('Event emitted', value) }) } // 关键步骤:让Emitter的原型继承自EventEmitter的原型 Emitter.prototype = Object.create(EventEmitter.prototype) // 修正constructor指向,避免原型链混乱 Emitter.prototype.constructor = Emitter const myEmitter = new Emitter() myEmitter.emit('event', 'hello') // 现在可以正常触发事件啦
方案2:ES6 Class语法(更简洁推荐)
用Class的extends语法会自动帮你处理原型链,写起来更省心:
const EventEmitter = require('events') class Emitter extends EventEmitter { constructor() { super() // 等价于EventEmitter.call(this) this.on('event', value => { console.log('Event emitted', value) }) } } const myEmitter = new Emitter() myEmitter.emit('event', 'world')
简单说,就是得让你的自定义构造函数的原型链指向EventEmitter的原型,这样实例才能继承到那些核心方法~
内容的提问来源于stack exchange,提问作者ask4you
相关产品推荐
相关产品推荐

