0

Possible Duplicate:
Simplest/Cleanest way to implement singleton in JavaScript?

  1. What is the use of Singleton class?
  2. Can anyone give me a scenario where Singleton class be applied?{ If i am developing an Mobile App using JavaScript, what could be my Singleton Class here }
  3. Any examples on how to create Singleton Class in JavaScript.
Community
  • 1
  • 1
John Cooper
  • 7,343
  • 31
  • 80
  • 100
  • http://en.wikipedia.org/wiki/Singleton_pattern – jantimon Jun 10 '11 at 14:14
  • 1
    If you want to have a singleton, just create an object. – Felix Kling Jun 10 '11 at 14:15
  • 2
    Javascript doesn't have classes. –  Jun 10 '11 at 14:17
  • @delnan functions are first class objects in Javascript. There isn't a actual implementation but Yes Javascript is OOP'ed if you ask me – Deeptechtons Jun 10 '11 at 14:21
  • @Deeptechtons "OOP'ed" does not mean it needs classes – Raynos Jun 10 '11 at 14:22
  • @Deeptechtons: JS is most certainly object-oriented. But it doesn't implement objects as instances of classes, it has just objects and objects inherit from other objects. Talking of classes in JS is not just a factual error, it shows a confusion about the basics of the language. –  Jun 10 '11 at 14:23

2 Answers2

2
  1. A class implements the Singleton pattern when it is desired that there should only be one instance of that class extant at any given time.

  2. The example that I'm most familiar with is if you are, for example, creating a game and you only want one player-controlled entity to exist at a time; the player entity would use the Singleton pattern.

  3. Actually using Singletons in Javascript is kind of wonky, but Dynamic's link above makes sense.

jszpila
  • 676
  • 9
  • 24
  • 2
    Singletons in JavaScript do not make sense. Since js only has objects. You don't create a singleton class, you just make a single object. The pattern is completely unapplicable to JS because your thinking in terms of classical OOP land. – Raynos Jun 10 '11 at 14:24
  • https://stackoverflow.com/a/72862943/8168578 here i share modern Javascript class with singelton pattern – Marek Lisiecki Jul 05 '22 at 10:56
0

Its useful when you want to share an object across classes.

Chris
  • 9
  • 1