DEV Community

Cover image for Singeltons in JavaScript not needed?
decker
decker

Posted on

1

Singeltons in JavaScript not needed?

Yes you can implement the singelton pattern in JavaScript with a class, but is it useful or do we need it?

I don't think so, because simply using an object literal is sufficient and always a singelton, if you place it in his own file.

This little example shows it.

console.log('A imported')

const state = {
  isLoading: false,
  hasError: false
}

export default state
Enter fullscreen mode Exit fullscreen mode
import state from './A.js'
console.log('B imported')

const api = {
  getData () {
    state.isLoading = true
  }
}

export default api

Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <script type="module">
    import state from './A.js'
    import api from './B.js'
    console.log(state)
    api.getData()
    console.log(state)
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The console shows only one A imported and the state is shared.

Image description

The reason is, JavaScript imports each file/module only once and modules are singletons per definition. If a module is imported multiple times, only a single instance of it exists and it is evaluated only once after load.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more