Using nested classes to simulate namespaces in ES6

2020-06-27 07:44发布

问题:

I have a file, Services.js which I am trying to load all of my individual services in. These are exposed as singletons.

Services.js

var Services = { };

export default Services;

I then want Sample Service nested under Services, so I could invoke for example Services.Sample.Operation()

`SampleService.js'

import Services from './Services';

Services.Sample = {

    Operation: function() {
        alert('operation!') 
    }
};

export default Services.Sample;

Then, I try and import:

import Services from './services/Services';
import SampleService from './services/SampleService';

alert(Services);         // yields '[object object]'
alert(SampleService);    // yields '[object object]'
alert(Services.Sample);  // yields 'undefined' <--- This is the one I actually want to use

How can I get it so I can refer to Services.Sample rather tan SampleService. How can I make SampleService become nested under Services?

回答1:

Your way doesn't work because you're importing Services.js in SampleService.js, but the Services variable is not the 'original' Services variable from Services.js.

What I'd do is something like this:

SampleService.js:

SampleService = {

    Operation: function() {
        alert('operation!') 
    }
};

export default SampleService;

Services.js:

import SampleService from './SampleService';

var Services = { };
Services.Sample = SampleService;

export default Services;

and then:

import Services from './services/Services';

alert(Services);         
alert(Services.Sample);

export default Services;

This does also seem to make more sense to me regarding basic (in)dependencies and consistency of your modules (define what Services can do in Services.js not SampleService.js, SampleService could be independent of Services, the module loading Services.js should not depend on SampleService.js as well as that might change later, ...).