2

I have some code:

"use strict";

class Node {
  constructor() {

  }
}

class Person extends Node {
  constructor() {

  }
}

const fred = new Person();

Run in Node v4.2.4 it gives the error:

ReferenceError: this is not defined
    at Person (/home/chris/test.js:12:3)

Where line 12 is the closing bracket of Person::constructor.

Why can't I extend the Node class?

fadedbee
  • 42,671
  • 44
  • 178
  • 308

2 Answers2

6

You need to call the super constructor:

class Person extends Node {
  constructor() {
    super();
  }
}

For reference, I actually tested your code on es6fiddle, which gave a very nice and descriptive error message in the console.

Uncaught SyntaxError: unknown: Line 10: Derived constructor must call super()

   8 | 
   9 | class Person extends Node {
> 10 |   constructor() {
     |   ^
  11 | 
  12 |   }
  13 | }
Community
  • 1
  • 1
Joseph Young
  • 2,758
  • 12
  • 23
3

In your Person class's constructor, it is necessary to call super():

"use strict";

class Node {
  constructor() {

  }
}

class Person extends Node {
  constructor() {
    super();
  }
}

const fred = new Person();

This is mandatory, as stated in Mozilla's documentation for super.

The error message is not really explicit, granted, but I guess it is caused by the internal implementation of the inheritance. Since you don't call the parent class's constructor, some internal use to "this" must lead to the "this" resolution problem, when you instantiate your fred object.

j11e
  • 371
  • 2
  • 6