JavaScript: Inherit static object like static primitive

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?

Answer

A.arr is as distinct from B.arr as A.id is from B.id. The issue is that A.id++ is equivalent to A.id = A.id + 1, which replaces the value of A.id with a new value. A.arr.push('a') does not replace the contents of A.arr, which is a reference to the same object in B.arr.

This has nothing to do with classes or static members. Observe:

let a = [];
let b = a;
a.push(1);
console.log('a refers to the same object as b; change that object, both a and b change');
console.log(`a=${a}; b=${b}`);
b = [...a, 2];
console.log('b refers to a different object from a');
console.log(`a=${a}; b=${b}`);

I assume you are asking how to assign a new object to every subclass. Since AFAIK JavaScript doesn’t have subclass hooks, I believe the only way would be to do it manually for each subclass.

class Base {
  static arr = [];
}

class A extends Base {
  static arr = [];
}
class B extends Base {
  static arr = [];
}

A.arr.push(1);
B.arr.push(2);
console.log(`A.arr=${A.arr}; B.arr=${B.arr}`);

Another approach is to use a static getter to do it for you. For example, this might work:

class Base {
  static _arr = null;
  static get arr() {
    return (this._arr ??= []);
  }
}

class A extends Base {}
class B extends Base {}

A.arr.push(1);
A.arr.push('a');
B.arr.push(2);
B.arr.push('b');
console.log(`A.arr=${A.arr}; B.arr=${B.arr}`);