Object of classes, using "extends" to reference another class in the same object

1 day ago 2
ARTICLE AD BOX

The code cannot possible because of the lack of time travel in JavaScript. You cannot extend a class that currently does not exist and is being created at the same time as the extends.

The issue boils down to trying to use the value of what is currently being assigned:

foo = foo + 1;

The two class creations need to be separated in terms of time of execution:

Either by making them separate statements

const Foo = class { } A = { Foo: Foo, Bar : class extends Foo { constructor (){ super() console.log("test") } } } var a = new A.Bar();

Or by delaying the evaluation of class extends A.Foo until A.Foo exists, which can be done with a getter (code runs when A.Bar is accessed).

A = { Foo: class { }, get Bar(){ return class extends A.Foo { constructor (){ super() console.log("test") } } } } var a = new A.Bar();

However, the best way is to not attempt this initialisation at all. There is no need to do it all in the object initialiser. Keeping the class declarations separate makes the code easier to read and less error prone

class Foo { } class Bar extends Foo { constructor (){ super() console.log("test") } } const A = { Foo, Bar }; var a = new A.Bar();
Read Entire Article