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!