0

I'm creating a kind of factory class, where I store some pointers to class-level functions in a map, and the main factory function uses the map to determine how to create the service to be returned. Below is a simplified version:

class SpecificService {}
class DefaultService {}

class ServiceFactory {
  constructor() {
    this._serviceInstances = new Map();
    this._serviceCreators = new Map([['someID', this._getSpecificService]]);
  }

  getService(identifier) {
    const serviceGetter = this._serviceCreators.get(identifier) || this._getDefaultService;
    return serviceGetter();
  }

  _getSpecificService() {
    return this._getServiceInstance(SpecificService);
  }

  _getDefaultService() {
    return this._getServiceInstance(DefaultService);
  }

  _getServiceInstance(serviceConstructor) {
    let instance = this._serviceInstances.get(serviceConstructor);
    if (!instance) {
      instance = new serviceConstructor();
      this._serviceInstances.set(serviceConstructor, instance);
    }
    return instance;
  }
}

Usage of this is as follows:

const factory = new ServiceFactory();
const service = factory.getService('someID');
// expect(service).toBeInstanceOf(SpecificService);

However I'm running into an error where the getServiceInstance appears to be undefined

Cannot read property 'getServiceInstance' of undefined

I'm expecting the chain of calls to be:

  • getService -> _getSpecificService -> _getServiceInstance

However what I'm seeing is:

  • getService -> _getSpecificService -> undefined

What's going on here? I'm storing a reference to this._getSpecificService (which has a reference to this._getServiceInstance) in a map, however when the former is called, the latter does not appear to exist?

devklick
  • 2,000
  • 3
  • 30
  • 47

0 Answers0