vendredi 13 mai 2016

Singleton pattern vs. Global variable use cases in Javascript?

Background

I'm teaching myself programming (focused on JS at the moment) and having trouble conceptualizing Singleton design patterns. The (http://ift.tt/1engPsa) introduction states:

"[S]ome who are critical of the singleton pattern [consider it to introduce] global state into an application." (1st paragraph)."

The body of the article states: "Singletons are often preferred to global variables because: They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables."

Considered together, these statements muddle my understanding of what singletons are and when they should be used in place of global variables.

The Question/Ask

Could anyone share an example scenario that could be implemented in JS with either a Singleton or Global Variable and provide a use case for when each strategy would be appropriate? Analogies and metaphors alongside code are extra helpful!

Aucun commentaire:

Enregistrer un commentaire