Consider the following code:
class A { protected sum: number; constructor(protected x: number, protected y: number) { this.sum = this.x + this.y; } } class B extends A { constructor(x: number, y: number) { super(x, y); } }
Calling super in the ctor of class B calls the ctor of class A , and if we look at the compiled javascript code:
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(x, y) { this.x = x; this.y = y; this.sum = this.x + this.y; } return A; }()); var B = (function (_super) { __extends(B, _super); function B(x, y) { _super.call(this, x, y); } return B; }(A));
It should be clear why we are doing this, because otherwise everything that happens in ctor A will not happen, that is, the members x , y and sum will not be assigned to instances of class B
Then you may ask, “OK, OK, but why doesn't this happen automatically? Why doesn't the compiler just call super for me?”
This is a fair question, and I can think of 2 main reasons:
(1) Because sometimes you want to do something before calling super , for example:
class A { protected sum: number; constructor(protected x: number, protected y: number) { this.sum = this.x + this.y; } } class B extends A { constructor(x: number, y: number) { if (x % 2 === 0) { super(x, y); } else { super(x + 1, y); } } }
You must call super before you access this in ctor B
(2) It makes it clear that this is what happens, otherwise you cannot expect this to happen because you do not see it.
This requirement applies only to constructors, class methods are not required to call them super, but you can do this if you want to execute the functionality of the parent method.