Home >Web Front-end >JS Tutorial >How Can I Properly Implement a Static Class or Singleton Pattern in JavaScript?
Understanding Javascript Static Function Expressions: The GameData Case
In Javascript, function expressions that utilize the new keyword are not static in the same sense as their C# counterparts. Rather than creating a genuinely static class, this approach leaks the constructor property and generates a prototype object that is likely not intended.
A Deeper Dive into the GameData Example
The provided example, gameData, demonstrates the creation of a single instance of a "class" using a function expression with the new keyword. However, the inclusion of the constructor property allows for the instantiation of additional objects, making the "class" non-static.
Alternative Singleton Approaches
To achieve a true singleton pattern in Javascript, consider the following methods:
Singleton Pattern Implementation
The below code illustrates the Singleton Pattern using a constructor function:
function GameData() { if (this.constructor.singleton) return this.constructor.singleton; else this.constructor.singleton = this; // Private and public members initialization } GameData.prototype.storageAvailable = function () { // Availability check logic }; var gameData = new GameData(); var gameData2 = new GameData(); console.log(gameData === gameData2 === GameData.singleton); // Outputs true
This approach ensures that subsequent instantiation attempts always return the same GameData instance, establishing a true singleton behavior.
The above is the detailed content of How Can I Properly Implement a Static Class or Singleton Pattern in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!