The singleton pattern is defined to ensure that a class has only one instance and provides a global access point to access it.

I’m going to use a closure to return an instance, and then I’m going to conditionally return it and initialize it so that we can only get one instance every time we new it

For example, global masks and global variables are good for singletons because none of us want to have two masks

const Singleton = (function () {
  let instance = null;

  return function () {
    if (instance) {
      return instance;
    }
    // Your business logic
    / / such as
    this.name = 'nanshu';
    this.age = 18;

    return (instance = this); }; }) ();// test
const a = new Singleton();
const b = new Singleton();

console.log(a === b); // true
console.log(a); // { name: 'nanshu', age: 18 }
Copy the code