In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init
, and class B overrides the init
function.
a.ts
export default class A {
constructor() {
this.init();
}
init() {
console.log("A.init()")
}
}
b.ts
import A from "./a"
export default class B extends A {
public bx = 3;
public by = 10;
public bz = 0;
constructor() {
super();
}
init(){
this.bx = 5;
this.bz = this.by;
console.log("B.init()")
}
}
When compiled with tsc
, the resulting js files looked like this:
a.js
export default class A {
constructor() {
this.init();
}
init() {
console.log("A.init()");
}
}
b.js
import A from "./a";
export default class B extends A {
constructor() {
super();
this.bx = 3;
this.by = 10;
this.bz = 0; //even worse
}
init() {
this.bx = 5;
this.bz = this.by;
console.log("B.init()");
}
}
One might question why there is a line this.bx = 3;
after super()
in the constructor of b.js
. It seems redundant since the property should already be initialized. This optimization could be handled better by the compiler to avoid unnecessary assignments.
Comparing to c# code:
using System;
public class Program
{
public static void Main()
{
B b = new B();
Console.Out.Write("x: " + b.x + " y: " + b.y);
}
}
class A {
public A() {
init();
}
public virtual void init() {
}
}
class B : A {
public int x = 3;
public int y = 10;
public int z = 4;
public B() : base() {
}
public override void init() {
this.x = 5;
this.y = this.z;
}
}
You will get x: 5 y: 4
.