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

How to Implement the Singleton Pattern in JavaScript?

Linda Hamilton
Release: 2024-12-04 00:00:17
Original
765 people have browsed it

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 () {
    // ...
  }
};
Copy after login

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 () {
    }
  };
})();
Copy after login

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

To prevent modifications, use Object.freeze:

Object.freeze(myInstance);
Copy after login

In ES6, use ES Modules:

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

function privateFn () {
  // ...
}

export default {
  method1() {
    // ...
  },
  method2() {
    // ...
  }
}
Copy after login

Then import it:

import myInstance from './my-singleton.js'
// ...
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template