The following code fails:
var EventEmitter = require('events');
class Foo extends EventEmitter{
constructor(){
this.name = 'foo';
}
print(){
this.name = 'hello';
console.log('world');
}
}
var f = new Foo();
console.log(f.print());
and prints error
this.name = 'foo';
^
ReferenceError: this is not defined
However when I am not extending EventEmitter it works fine.
Why is this happening and how can I resolve it? running nodejs 4.2.1
Any listeners for the error event should have a callback with one argument to capture the Error object and gracefully handle it. If an EventEmitter emits an error event, but there are no listeners subscribed for error events, the Node. js program would throw the Error that was emitted.
When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded. The following example shows a simple EventEmitter instance with a single listener.
on(event, listener) and eventEmitter. addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener's array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times.
Finally, we return an object of EventEmitter from the function. So now, we can use the return value of LoopProcessor function to bind these events using on() or addListener() function.
When you are extending another function, then super(..)
should be the first expression in your constructor
. Only then you can use this
.
var EventEmitter = require('events');
class Foo extends EventEmitter {
constructor() {
super();
this.name = 'foo';
}
print() {
console.log(this.name);
}
}
new Foo().print();
// foo
It is like this because, the class you are deriving from, should be given a chance to set the variables, before the current class overrides them.
Also, implicitly calling the super()
means that, we are passing undefined
to the parameters which are declared in the constructor
of the parent. That is why it is not done, by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With