How to resolve "this is not defined" when extending an EventEmitter?

The following code does not work:

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 an error

  this.name = 'foo'; ^ ReferenceError: this is not defined 

However, when I do not distribute EventEmitter, it works fine.

Why is this happening and how can I solve it? running nodejs 4.2.1

+8
javascript ecmascript-6 class
source share
1 answer

When you extend another function, then super(..) should be the first expression in the constructor . Only then can you use this .

 var EventEmitter = require('events'); class Foo extends EventEmitter { constructor() { super(); this.name = 'foo'; } print() { console.log(this.name); } } new Foo().print(); // foo 

This is similar to the fact that the class you are leaving should be given the opportunity to set variables before the current class redefines them.

In addition, an implicit call to super() means that we pass undefined parameters declared in the constructor parent. That is why this is not done by default.

+16
source share

All Articles