I have the following JavaScript classes, where in the onClick
method of the Lesson
class the lessonObj
property is NOT defined, though the init
method of the Lesson
class is correctly called. How do I have to change the code, so that it works?
Thanks
class Item
{
name;
constructor(name)
{
this.name = name;
}
}
class Page
{
pageObj;
constructor()
{
this.init();
}
init()
{
this.pageObj = new Item('John');
}
}
class Lesson extends Page
{
lessonObj;
constructor()
{
super();
}
onClick(event)
{
alert(this.pageObj.name);
alert(this.lessonObj.name);
}
init()
{
super.init();
this.lessonObj = new Item('Mary');
document.addEventListener('click', event => this.onClick(event));
}
}
new Lesson();
Click somewhere
2
Answers
Here is the correct code
It’s this line here:
That line basically adds a
this.lessonObj = undefined
to the constructor after thesuper()
call but before any other code.So the overall execution order is this:
so that
this.lessonObj = new Item('Mary');
frominit()
is later overwritten withthis.lessonObj = undefined;
in theconstructor()
.That’s why at the time you get into your click handler,
this.lessonObj
is empty.Here a rundown (in the correct order) of the code executed when you do
const me = new Lesson();
. I’ve commented out the function calls since I’ve inlined their content.There’s not the one solution for this.
or even this
or if you want to keep
init()
but want to ensure thatinit()
is called after all the constructors, you could use a factory function:Or you could take a
fluid interface
approach, letinit()
alwaysreturn this
and write something like