1

I have two classes namely A and B respectively. The class definitions are as shown below.

class A {

    constructor(){
        ...
    }

    ...
}

//Implementation 1

class B extends A {
    constructor(){
        this.childProperty = "something"; // this is undefined.
    }
}

//Implementation 2

class B {
    constructor(){
        this.childProperty = "something"; // this is not undefined.
    }
}

Why is this undefined in Implementation 1 and not in Implementation 2? What am I doing wrong here?

Jaseem Abbas
  • 5,028
  • 6
  • 48
  • 73
  • How are you creating an object `A` and an object `B`? If you're doing `B()` and not `new B()`, that could explain the `this` issue. – jfriend00 Jan 29 '16 at 16:04

2 Answers2

16

You need to call super() first:

class B extends A {
   constructor() {
     super();
     this.childProperty = "cool"
   }
}

JsFiddle

Dieterg
  • 16,118
  • 3
  • 30
  • 49
  • why do we need to call `super()`? – Jas Nov 23 '16 at 11:54
  • To make sure you inherit all properties/methods from your derived class. This is only necessary if you add a constructor yourself. Behind the scenes this will do something like `_super.call(this)`. [Use this typescript playground as a reference](https://www.typescriptlang.org/play/#src=class%20X%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0Aclass%20Y%20extends%20X%20%7B%0D%0A%20%20%20%20constructor()%20%7B%0D%0A%20%20%20%20%20%20%20%20super()%3B%0D%0A%20%20%20%20%7D%0D%0A%7D) – Dieterg Nov 23 '16 at 12:11
  • is there a documentation that stated it is required for inherited class? – O.O May 24 '17 at 07:08
  • Yes, read through the documentation over [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) – Dieterg May 24 '17 at 12:12
5

Try adding super to your class:

class B extends A {
    constructor(){
        super()
        this.childProperty = "something"; 
    }
}
Nader Dabit
  • 52,483
  • 13
  • 107
  • 91