Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resolve 'this is not defined' when extending EventEmitter? [duplicate]

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

like image 299
guy mograbi Avatar asked Jan 22 '16 13:01

guy mograbi


People also ask

What happens if an error event is emitted through an EventEmitter and nothing listens to it?

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.

How are functions called when an EventEmitter object emits an event?

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.

How do I add a listener to EventEmitter?

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.

What is used to returning from EventEmitter object?

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.


1 Answers

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.

like image 171
thefourtheye Avatar answered Oct 14 '22 23:10

thefourtheye