When writing JavaScript-based games I typically use object pooling to reduce GC work. This typically involves applying constructors to existing objects, e.g.:
constructor.apply(object, arguments);
This way, constructor functions can be used both for creating new objects and for 'setting up' existing objects. (I've seen other pooling systems that do something similar.)
The problem is that JavaScript class constructors (that is, created using the 'class' keyword) can only be invoked with 'new', meaning the above code no longer works.
My question is, is there a practical way to use pooling with classes created via 'class'? Or is the best option here to give up on 'class' and just set up (so-called) classes 'manually' without using the 'class' keyword?
Instead of re-apply the constructor, which is a bad thing and confusing, you just write your initialization logic in a init
method, and call this.init()
in constructor.
When you want to re-initialize an object, just call obj.init()
and everyone understands it.
class Foo {
constructor(...args) {
this.init(...args)
}
init(val) {
this.val = val
}
}
const f = new Foo(42)
console.log(f.val)
f.init(43)
console.log(f.val)