10

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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
guy mograbi
  • 27,391
  • 16
  • 83
  • 122

1 Answers1

21

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497