Skip to content Skip to sidebar Skip to footer

Avoid Exporting Singleton In Es6

As I have seen, ES6 exports singletons for object literals: // module A export const singleton = { user: 'a', asd: 'b' } setTimeout(() => console.log(singleton.user), 5000)

Solution 1:

ES module is evaluated only once on first import, this efficiently makes module exports singletons.

exportconstgetObject = () => ({ user: 'asd', asd: 'b' })

is factory function and it's perfectly valid in this case, it's preferable for data-only object that has no inheritance and no methods.

A class is a suitable alternative (a bit less efficient than factory function but a better choice if there are methods):

exportclassA {
  constructor() {
    this.user =  'asd';
    this.asd = 'b';
  }
}

Since React is in use, it's safe to assume that the code is transpiled with Babel, so class fields proposal can be used. They aren't available in ES6 and provide syntactic sugar for constructor code listed above:

exportclassA {
  user = 'asd';
  asd = 'b';
}

Solution 2:

When a module is loaded, it is cached. So, when someone else loads it again, no new code is run. The previous exports are just returned.

That works, but I was thinking, is there a cleaner way to export new instances? Or the only way is exporting that function that I should call in B to get my new instance?

If you want a new instance each time, you have to export a function that you can call to get a new instance. There is no other way because loading a previously loaded module does not run any additional code - it just returns the previous cached exports.

You can either export a factory function (like in your example):

exportconst myFactory = function() {
   return { user: 'asd', asd: 'b' };
}

Or you can export a constructor function (that the caller would call with new to get a new object).

exportclassmyObj {
   constructor() {
       this.user = 'asd';
       this.asd = 'b';
   }
   checkUser() {
       // some code here that operates on instance data
   }
}

Either the factory function or the constructor function would work just fine. If there are no methods and you just want a plain object, then the factory function is simpler. If there are methods, then the class probably makes more sense.

Post a Comment for "Avoid Exporting Singleton In Es6"