I have the following Code:
class Base {
static id = 5;
static arr = [];
}
class A extends Base {}
class B extends Base {}
This gives every sub-class its own static id property:
A.id++;
console.log(A.id) : 6 (Only this one got increased)
console.log(B.id) : 5
console.log(Base.id) : 5
However this is not the case for Objects. When the Subclass gets created, a reference to Base-Class's Object is passed, instead of (in the case of Primitives) a simple copy. This gives the following result:
A.arr.push('a');
console.log(A.arr) : ['a']
console.log(B.arr) : ['a'] (I want this to stay empty)
console.log(Base.arr) : ['a'] (I want this to stay empty)
How would I have to change static arr = []; so that each sub-class gets its own static array?
static arr = [];inclass Aandclass Bas well.arrandidfor? This smells like a design issue. What do your subclasses represent?Game.arrshould contain all runningGameinstances, no matter what subclass they have. If you want a separate list that contains only TicTacToe games, make a separate list. It's not the responsibility of theGameclass to do that.Game -> TwoPlayerRoundBasedGame -> TicTacToeis really the best design. Maybe they should be mere interfaces? Maybe they should be mixins? Maybe you should use composition instead?