Description
I have a problem I've encountered a few times:
class BaseClass
{
constructor()
{
this.init();
}
protected init()
{
}
}
class ChildClass extends BaseClass
{
constructor()
{
super();
}
protected init()
{
var div = document.createElement("div");
console.log(this.onClick); // undefined
div.addEventListener("click", this.onClick);
}
private onClick = (event: MouseEvent) =>
{
// ...
}
}
var child = new ChildClass();
The problem is that in the init of ChildClass, "onClick" is still undefined because in the compiled JS it is only defined after the super call. This comes up generally when I call functions in the super class that are likely to be overridden in child classes and the child implementations use arrow functions defined in the child class.
I was wondering what was the reason behind this order and wouldn't it be possible to reverse it (ie. define arrow functions first, call super afterwards).
I think it's related to this error message which pops up if you try to call init manually before super():
"A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties"
Related issues are:
https://typescript.codeplex.com/discussions/444975
http://typescript.codeplex.com/workitem/91
My view of this is that the only reason I'm using arrow functions generally is to make sure the scope (this) is correct, so ideally it would be good to be able to work with them just like if they were "non-arrow", normal prototypical functions.