3

I've been in a debate on whether exporting an already instantiated class makes sense or not:

class myClass{
  constructor(){
    console.log("Hello");
  }
  foo(){
    console.log("Do something!");
  }
}

const cls = new myClass();
export default cls; 

Then we consume it like this:

import myClass from './js/myclass';
myClass.foo();

I think this defeats the purposes of classes. My friend says, that this allows you to "just use it" when you require/import the file; similar to NodeJS path, fs, etc... functions.

Therefore, could it be considered a bad practice, or is this perfectly acceptable?

Jose A
  • 10,053
  • 11
  • 75
  • 108
  • 3
    If you don't use it as a class, don't create a class. Just have a few local variables, and export functions that can access these variables. – PeterMader Aug 12 '17 at 15:27
  • @PeterMader Yes. That makes more sense. – Jose A Aug 12 '17 at 15:30
  • 1
    Just do `export default { foo() { ... } };` There's no need for a class. – 4castle Aug 12 '17 at 15:30
  • 2
    More important that being able to just use it is the fact that you are getting a single instance that is shared when imported in different places. That can be very useful or not depending on what you need. – Mark Aug 12 '17 at 15:48
  • 2
    related, if not duplicate: [Differences between creating a new class to using export const](https://stackoverflow.com/q/39076190/1048572) – Bergi Aug 12 '17 at 15:55
  • Possible duplicate of [Differences between creating a new class to using export const](https://stackoverflow.com/questions/39076190/differences-between-creating-a-new-class-to-using-export-const) – Jose A Aug 12 '17 at 16:16
  • Yes this make sense. This way you can create a singleton. It's not a real singleton, but for most cases good enough. – Jan Franta Aug 12 '17 at 19:05
  • There are certainly benefits to using this pattern. In your contrived example maybe not so much, but when your class has dependencies that you pass in the constructor it makes unit testing much easier. When you export functions you don't have control over the dependencies in a test environment without using nasty hacks that change the behavior of the module system. – Jake Holzinger Jan 13 '20 at 22:01

1 Answers1

1

Yes, it is bad practice.

We don't recommend exporting an evaluation (e.g. new myClass()) for several reasons.

In this case, the module exports the result which is only evaluated once. This is rarely the desired outcome, but if it is, a Singleton pattern should be used instead. Some ES6 module benefits are lost (tree-shaking and faster access to imports), it makes imports slower and makes them possible to cause side-effects which should rather happen upon invocation. The drawbacks can be avoided via exporting a function or class.

See also:

thisismydesign
  • 21,553
  • 9
  • 123
  • 126