I'm trying to write a fake downloader which basically sleeps for certain interval and emits a 'downloaded' event. I also want to have my own variable that tracks the number of events emitted. This piece of code throws the following error:
ReferenceError: this is not defined
Code:
'use strict';
const EventEmitter = require('events');
class Downloader extends EventEmitter{
constructor(){
this.totalEmitted = 0;
}
download(delaySecs){
setTimeout(() => {
this.emit('downloaded',delaySecs);
this.totalEmitted ++;
},delaySecs*1000)
}
}
module.exports = Downloader;
where as, if I comment this.totalEmitted, it works fine.
UPDATE:
When I completely eliminate the constructor it started working fine.
And even using an empty constructor is causing the this Reference error.
I'm not sure if the constructor is yet supported in node 4.4.5.
Work around:
'use strict';
const EventEmitter = require('events');
class Downloader extends EventEmitter{
download(delaySecs){
setTimeout(() => {
if(this.totalEmitted == undefined) this.totalEmitted = 0;
this.totalEmitted ++;
this.emit('downloaded',delaySecs,this.totalEmitted);
},delaySecs*1000)
}
}
module.exports = Downloader;