Question

So, we all know that ES6's introduced syntax is definitely sugar over what we've been doing, previously. That being said, we still don't have namespaces (which would be nice...)

The problem that I'm trying to solve is converting old code into es6. This old code was doing something like:

window.foo = {
    init: function() {

    },
    otherFoo: {
        init: function() {

        }
    }
}

I was able to have my "modules" in separate files, and add them to my global "foo" that existed in window.

What I'd like to do instead, is create my separate modules, import them into my main JS file, and nest my classes within foo, like so:

import OtherFoo from './otherfoo';

class Foo {
    static init() {

    }
    static get OtherFoo() { 
        return OtherFoo;
    }
}

It works, so it's not a question if how I can make it work, it's a question of whether or not I should? We in the javascript community tend to do things just because we can, but I like to avoid that line.

Was it helpful?

Solution

I know of no good reasons not to do it if the organization helps. I consider your classes and static getters to be an internal implementation detail that can expose a pattern that's already used heavily in popular JS libraries. Many libraries already expose a single object hash with types, so this isn't much different.

I see no difference between that and, say:

// foo.js
module.exports = {
   OtherFoo: require('./otherFoo.js')
   OtherFoo2: require('./otherFoo2.js')
}

Consider this fictional version of mongoose in es6 that uses classes:

// mongoose/index.js
export default class Mongoose {
    constructor() {
    }

    static get model() { return require('./model.js'); }
}

//mongoose/model.js
export default class Model {
}

And that can be used just like the real mongoose with:

var mongoose = require('mongoose');

new mongoose.model(...);

OTHER TIPS

Your method will work but because you are using a getter to return an instance of a class you are actually returning a new definition of an instance of a class each time. So later on, if you want to use instanceof Foo.OtherFoo, you will find it returns false every time.

Licensed under: CC-BY-SA with attribution
scroll top