我正在尝试编写一个简单的类来在接收到事件时触发原型函数,但是我遇到了范围问题。出于某种原因,我无法访问Stream
上下文,即使我已将事件侦听器绑定到它。
function Stream(report) {
this.report = report;
this.stream = new api.getTagStream(report.tag);
this.stream.on('error', this.onError.bind(this));
this.stream.on('data', this.onData.bind(this));
return this;
}
Stream.prototype.onError = err => {
// Had an error
}
Stream.prototype.onData = data => {
console.log(this.report); // undefined
}
new Stream({ tag: 'sometag' });
onData
内的日志应显示报告对象,但返回undefined。
答案 0 :(得分:1)
将箭头功能替换为"正常"功能声明
function Stream(report, stream) {
this.report = report
stream.on('error', this.onError.bind(this))
stream.on('data', this.onData.bind(this))
}
Stream.prototype.onData = function(data) {
console.log(this.report, data) // { tag: 'some tag' } 'some passed data'
}
const EventEmitter = require('events')
const stream = new EventEmitter()
new Stream({ tag: 'some tag' }, stream)
stream.emit('data', 'some passed data')