Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript export class or object [closed]

What is the best practice for exporting?

class MyUtils {
  print() {...}
  convert() {...}
}
export default new MyUtils();

Or:

const myUtils = {
  print() {...}
  convert() {...}
}
export default myUtils;

Or something else?

Note: this should be a singleton, no more than 1 instance

like image 619
Vic Avatar asked Aug 12 '16 15:08

Vic


2 Answers

Your second option should work for the singleton and that is what I use normally. From Felix's comment, I get that modules are singleton's and option 1 would also work. I am still inclined to go with the second option since the code makes my intention to use singleton very clear.

const myUtils = {
  print() {...}
  convert() {...}
}

export default myUtils;
like image 99
randominstanceOfLivingThing Avatar answered Oct 21 '22 12:10

randominstanceOfLivingThing


Generally exporting an object as the default export is a bit of an antipattern. Your very best option would be to do

export function print() {...}
export function convert() {...}

then do

import * as utils from "./utils";

to avoid creating the object entirely, and rely on the module object itself to act as your namespace.

like image 42
loganfsmyth Avatar answered Oct 21 '22 12:10

loganfsmyth