Classical inheritance and association of objects

I am currently working on a project that uses the following inheritance structure:

var Type = function(a){ this.a = a; }; var SubType = function(a){ Type.call(this, a); }; SubType.prototype = Object.create(Type.prototype); SubType.prototype.constructor = SubType; 

Now I'm trying to add some pool of objects to the equation. The sample I'm currently using works something like (pseudocode):

 Type.new = function(){ if object available in pool reset popped pool object return pool object else return new Type() } var a = Type.new(); 

Of course, the problem with using these two patterns is that the constructor calls SubType, which will not draw from the type pool. Is there any way around this without going to the factory structure? That is, there is a way, in the constructor, to do something line by line:

 var SubType = function(){ build on top of instanceReturnedFromFunction() }; 

Knowing that this is not always consistent in different contexts, I would also like to preserve the inheritance structure, so that instanceof, etc. will work anyway:

+5
source share
1 answer

The problem with using this pattern is that the constructor causes SubType not to draw from the Type pool

In fact, this is not a problem, but a necessity. Type and SubType instances have different prototypes, you cannot use them interchangeably (and replacing prototypes does not work either ).
You will definitely need separate pools for all your classes. And you can use this .new factory approach without problems - although, of course, you have to programmatically create these plants:

 function pooledNew() { // `this` is the "class" constructor function if (!this.pool) this.pool = []; var instance = this.pool.length ? this.pool.pop() : Object.create(this.prototype); this.apply(instance, arguments); // reset / initialise return instance; } function makePooling(constr) { constr.new = pooledNew; constr.pool = []; var proto = constr.prototype; if (proto.constructor !== constr) proto.constructor = constr; if (typeof proto.destroy != "function") proto.destroy = function destroyInstance() { this.constructor.pool.push(this); }; return constr; } 

They are designed to work flawlessly with a subclass, in your example just

 makePooling(Type); makePooling(SubType); 

In ES6, subclasses even inherit the new method from their superclass constructors.

 class Type { constructor(a) { this.a = a; } destroy() { // overwriting default behaviour this.a = null; // for GC this.constructor.pool.push(this); } } makePooling(Type); class SubType extends Type { // you can use super calls in both "constructor" and "destroy" methods } 
+4
source

All Articles