4

I've been reading about ES6 modules and have noticed that classes are either exported as-is, or after being newed up.

For instance:

class Class1 extends SomeOtherClass {
   constructor() {
     super();
   }
   //Class1 methods and data here
}
export default new Class1();

..while in Class2.js:

class Class2 extends YetAnotherClass {
   constructor() {
     super();
   }
   //Class2 methods and data here
}
export default Class2;

Fair to assume that in the case of Class1 you've created a singleton, while with Class2 after importing it you can new up independent instances of it at will? If so, are there other scenarios for using new when exporting a class vs not?

jkj2000
  • 1,563
  • 4
  • 19
  • 26
  • Well, [don't use `new class` to create singletons](https://stackoverflow.com/a/38741262/1048572). ever. – Bergi Feb 15 '18 at 18:16

1 Answers1

1

Using new() produces a new object from the constructor function, and if you return that you will return the object only. Without using it, you return the function itself instead.

Feathercrown
  • 2,547
  • 1
  • 16
  • 30