0

I have a class that only requires one instance in my code. Is it better (and convention) to stick with the regular class, constructor and only create one instance of the class or to directly use the class without creating any instances by using static methods and properties? Something like this:

class Foo {
  constructor() {
    this.bar = []
  }
  foobar(x) {
    this.bar.push(x)
  }
}

let foo = new Foo()

Or like this:

class Foo {
  static bar = []
  static foobar(x) {
    this.constructor.bar.push(x)
  }
}

The second one takes up less space, but I'm not sure whether it adheres to OOP conventions.

EnderShadow8
  • 788
  • 6
  • 17
  • 2
    Doesn't make any sense to me, but some might choose it anyway. I'd use a plain object instead. – CertainPerformance Feb 06 '21 at 02:15
  • So without static? – EnderShadow8 Feb 06 '21 at 02:18
  • 2
    IMO, neither. I'd much prefer a plain object instead. Don't feel like you have to write JS as if you're in Java. – CertainPerformance Feb 06 '21 at 02:19
  • Well `Math` is an object with only static methods. It's not necessarily bad; it's a way of creating a namespace and of making code readable. – Pointy Feb 06 '21 at 02:20
  • And a class with a single instance is a "singleton", but I don't know how the trend winds are blowing lately whether that's a good thing or a bad thing. – Pointy Feb 06 '21 at 02:21
  • Also like (I think) Tanenbaum said, the great thing about "standards" is that if you don't like one, you can simply find another. – Pointy Feb 06 '21 at 02:23
  • I'm dealing with multiple constants related to this object in particular and I don't want lots of globals containing them, which is why I'm considering using a class. I definitely need a namespace for it, but I'm just unsure how standard this use of static properties and methods is. – EnderShadow8 Feb 06 '21 at 02:46
  • 1
    @EnderShadow8 the `.bar` array in your example isn't exactly a constant. If all you want is a namespace, then [use an object literal (or a module)](https://stackoverflow.com/a/29895235/1048572). Do not write a `class` with only `static` members that is never instantiated. If your singleton object is actually stateful, a class isn't a bad call - most likely you'll need different instances of it in the test code etc. – Bergi Feb 06 '21 at 06:32
  • The ```.bar``` was never meant to be a constant. I also have mutable properties in my use case. – EnderShadow8 Feb 06 '21 at 07:15

0 Answers0