Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
What is the difference between these two singleton approaches in JS?

The way to solve the singleton pattern in JS (TS actually) is looks like this (the best approach if you ask me):

export default class Singleton {
    private static _instance: Selection

    constructor() {
        if (Selection._instance) {
            return Singleton._instance
        } else {
            Singleton._instance = this
        }
    }
}

And then:

import Singleton from './Singleton.ts'

const singleton_1 = new Singleton()
const singleton_2 = new Singleton()

singleton_1 === singleton_2 // true

But in this scenario I have to create new variables every time I need that class.

I can achieve exactly the same the easier way:

class Singleton {
    constructor() {
        // some logic
    }
}

export default new Singleton()
import Singleton from './Singleton.ts'

const wut = Singleton.field
Singleton.method('do something')

Am I getting something wrong or the first approach is a little bit excessive and complicated and the second one just do the same thing in more obvious way?

I understand that if I have static fields in my class, I couldn't use it that way, but cases when you really need static fields are rare.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It is essential in a scenario where only one instance needs to be created, for example, a database connection. It is only possible to create an instance when the connection is closed or you make sure to close the open instance before opening a new one. This pattern is also referred to as strict pattern, one drawback associated with this pattern is its daunting experience in testing because of its hidden dependencies objects which are not easily singled out for testing.


let databaseInstance = null;

// tracks the number of instances created at a certain time
let count = 0;

function init() {
console.log(`Opening database #${count + 1}`);
//now perform operation
}
function createIntance() {
if(databaseInstance == null) {
databaseInstance = init();
}
return databaseInstance;
}
function closeIntance() {
console.log('closing database');
databaseInstance = null;
}
return {
open: createIntance,
close: closeIntance
}
}

const database = DatabseConnection();
database.open(); //Open database #1
database.open(); //Open database #1
database.open(); //Open database #1
database.close(); //close database

source: https://codesource.io/javascript-design-patterns/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda