Issue
How is it that Derived
is perfectly happy to call this.log()
but somehow doesn't know about this.value
? I'd have thought value
would be set before super()
is called?
How can Derived
have a value set by the constructor and still be accessed by this.log()
?
abstract class Base
{
protected abstract map() : void;
constructor()
{
this.map();
}
}
class Derived extends Base
{
constructor(private value : string)
{
super();
}
protected map(): void
{
this.log();
}
log()
{
alert(this.value);
}
}
const derived = new Derived("Hello world"); // Alerts "undefined"
Solution
@Fabrizio Gargiulo and @Shubham Wajo already mentioned the root problem which is from super()
initialization before this.value
assignment, but I'd give another way to fix it with a call stack trick.
Javascript only has a single thread, so all functions will proceed synchronously from top to bottom. super()
is not an exception for it, but we can delay the execution with setTimeout
for the call stack completed (all initializations are done).
abstract class Base
{
protected abstract map() : void;
constructor()
{
//this will run after `Derived` initalization completed
setTimeout(() => this.map())
}
}
class Derived extends Base
{
constructor(private value : string)
{
super();
}
protected map(): void
{
this.log();
}
log()
{
alert(this.value);
}
}
const derived = new Derived("Hello world"); //"Hello world"
Answered By - Nick Vu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.