#Clarity on javascript singletons

10 messages · Page 1 of 1 (latest)

proper scarab
#

So, in Java, you might use a class of a specific design called a singleton, in JavaScript you can also have a singleton class, but classes are essentially just objects in JavaScript, so you could also just directly instantiate an object literal const MyManager = { prop: 'value', more: 'stuff' } without the need for a special class pattern to keep the class from being instantiated multiple times. Also, with the benefit of explicit scoping (what with the ability to only export what you want, even if you chose to do a "singleton oop pattern" it wouldnt need all the single instance protections, as you could just not export the class, just an instance

proper scarab
#

Using a lobby manager as you suggest is a fine solution, but depending on your style it may be better to import the instance where you need or to inject it from high order functions directly into the objects that needs access (i.e. dependency injection), such that now to replace a unit, you can inject a different one in one place rather than needing to change a bunch of files imports

proper scarab
#

In some cases for example or may make more sense for a particular object to only be given reference to an instance of a single lobby vs the ability to find one from the manager

outer basalt
#

Clarity on javascript singletons

winged aspen
#

What's the question?

#

As a sidenote I highly recommend using Map over array, so you can just directly grab a lobby instead of iterating (via find)

#

class LobbyManager {
    #activeLobbies = new Map();
    #lobbyNumber = 1;
  /* all other stuff */

  getById (id) {
    return this.#activeLobbies.get(id)
  }
}
#

You can see how this is not only simpler but also has no iteration

#

for import/export I would:

module.exports = Object.seal(new LobbyManager())

/* */
const lobbyManager = require('....')
proper scarab
#

Looks ok to me. I've never felt the need to go so far as to freeze an object, but more power to you. I would agree that a Map would be the more idiomatic if your intent is to lookup by ID, but if the array stays below ~1000 it's probably still faster than a Map