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
import state from './A.js'
console.log('B imported')
const api = {
getData () {
state.isLoading = true
}
}
export default api
<!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>
The console shows only one A imported and the state is shared.
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.
Top comments (0)