Home >Web Front-end >JS Tutorial >How to Implement the Singleton Pattern in JavaScript?

How to Implement the Singleton Pattern in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 00:00:17768browse

How to Implement the Singleton Pattern in JavaScript?

How to Create a Singleton in JavaScript

In JavaScript, a singleton pattern ensures that only one instance of a class or object can be created. The simplest way to implement a singleton is through an object literal:

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

For private members, use a function expression:

var myInstance = (function() {
  var privateVar = '';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // All private members are accessible here
    },
    publicMethod2: function () {
    }
  };
})();

This pattern, known as the module pattern, encapsulates private members through closures.

To prevent modifications, use Object.freeze:

Object.freeze(myInstance);

In ES6, use ES Modules:

// my-singleton.js
const somePrivateState = []

function privateFn () {
  // ...
}

export default {
  method1() {
    // ...
  },
  method2() {
    // ...
  }
}

Then import it:

import myInstance from './my-singleton.js'
// ...

The above is the detailed content of How to Implement the Singleton Pattern in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn