Home > Web Front-end > JS Tutorial > How Can I Properly Implement a Static Class or Singleton Pattern in JavaScript?

How Can I Properly Implement a Static Class or Singleton Pattern in JavaScript?

Susan Sarandon
Release: 2024-12-19 18:45:14
Original
954 people have browsed it

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:

  • Object Literal: Create a simple object literal that lacks a constructor and prototype.
  • Revealing Module Pattern: Employ an Immediately Invoked Function Expression (IIFE) to establish closure-scoped variables and return the desired object.
  • Constructor ("Class"): Define a constructor function that, when called, always returns the same singleton object.

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
Copy after login

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!

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