Differences between creating a new class to using export const

Would there be a new instance every time I import A?

No, modules are only evaluated once.

Is one of the benefits of B the ability to use object destructuring and then use method1 as if it existed locally?

Yes, though it’s not called “destructuring”. They’re named imports (or named exports of the module), and they don’t nest and use a different syntax for aliasing.

Is one of the benefits of A the ability to initialize state in the constructor?

No. You can initialise module state just directly in the module scope as well, you don’t need a constructor function for that.

But yes, if you have state in the instances, it’s a good idea to use a class which you can instantiate multiple times. For that, you need to export the class itself, not an instance, of course.

Is the export default new … pattern valid at all?

No, it’s an antipattern for the reasons outlined above. Given the class is used nowhere else, it’s quite similar to the anonymous class antipattern. And exporting multiple named exports is much better than default-exporting objects anyway.

Leave a Comment