-2

Edit: this question is different from How to extend a class without having to using super in ES6? - although the answers are related, this is very obviously a different question. It relates to a specific error, and the two main classes involved Person and CreationEvent don't actually inherit from each other.

I have two ES6 classes, Person and CreationEvent (CreationEvent inherits from Event). I wish to to make a new CreationEvent when I make a new Person (as the CreationEvent is part of the events in the history of person's account).

Running new CreationEvent() on it's own works fine. However I can't run new Person().

Even with reduced version of the code still fails:

class Event {
    constructor() {
        this.time = Date.now()
        this.tags = []
    }
}

class CreationEvent extends Event {
    constructor() {
        this.description = "Created"
    }
}

class Person {
    constructor(givenName, familyName, email) {
        var creationEvent = new CreationEvent()
    }
}  

Running new Person() returns

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

How do I make a new ES6 Object in another Object's constructor?

mikemaccana
  • 81,787
  • 73
  • 317
  • 396

1 Answers1

6

You need to call super() in the CreationEvent class because it extends the Event class and needs te be initialized. Like this:

class CreationEvent extends Event {
    constructor() {
        super();

        this.description = "Created"
    }
}
Sjoerd de Wit
  • 2,072
  • 4
  • 23
  • 41
  • Thanks! But why does `new CreationEvent()` work without doing this? Also shouldn't a class that inherits from another class automatically run the constructor of the class it inherits from? – mikemaccana Oct 08 '18 at 13:24
  • 1
    @mikemaccana `new CreationEvent()` also doesn't work without the `super()` call. It's required to manually call the super constructor because javascript doesn't know when and how you'd like to call it. This allows you to e.g. manipulate the arguments to the super call. – jaap3 Oct 08 '18 at 14:17
  • @jaap3 You're right, I'd copied and pasted and not edited it when I tested it earlier. Thanks! – mikemaccana Oct 08 '18 at 14:20