SoFunction
Updated on 2025-03-10

Learning JavaScript Design Pattern Singleton Pattern

1. Definition

Ensure that a class has only one instance and provides a global access point to access it.
When you click the login button, a login floating window appears on the page. This login floating window is unique. No matter how many times the login button is clicked, this floating window will only be created once. Then this login floating window is suitable for creating in singleton mode.

II. Implementation principle

To implement a singleton, use a variable to mark whether an object has been created for a class. If so, the next time you get an instance of that class, you will directly return the object you created before.

3. Fake single case

Global variables are not singleton patterns, but in JavaScript development, we often use global variables as singletons.

var a = {};

Reduce naming pollution caused by global variables
(1) Use namespace

var namespace1 = {
  a: function(){},
  b: 2
}

(2) Encapsulate private variables using closures

var user = (function() {
  var _name = 'lee',
    _age = '25';
  return {
    getUserInfo: function() {
      return _name + ":" + _age;
    }
  };
})();

4. Lazy singleton: Only when needed can you create an object instance

var getSingle = function(fn) {
  var result;
  return function() {
    return result || (result = (this, arguments));
  };
};

// testfunction testSingle(){}
getSingle(testSingle)() === getSingle(testSingle)();  // true

5. Supplementary:

(1) Lazy loading

var lazyload = function() {
  (1);
  lazyload = function() {
    (2);
  }
  return lazyload();
}

lazyload();

(2) Preload

var preload = (function() {
  (1);
  preload = function() {
    (2);
  };
  return preload;
})();

preload();

I hope this article will be helpful to everyone to learn JavaScript programming.