Javascript singleton - to function or to json, that is the question - ΩJr. Software Articles and Products

This information lives on a web page hosted at the following web address: 'https://omegajunior.globat.com/code/'.

We can add singletons in javascript using various methods. Which is best for what purpose, and why?

A.E.Veltstra
Sunday, May 2, 2010

JSON method:
The singleton is an object with methods and properties.

Example:
var myNamespace = ({
message: 'hello, world!',
greeting: function () {
alert( myNamespace.message );
}
});


This method we've been using for years.


Function method:
The singleton is an anonymous function with methods and properties.

Example:
var myNamespace = function () {
var message = 'hello, world!';
var greeting = function () {
alert( message );
};
return ({
message: message,
greeting: greeting
});
}();


This method I see in samples of other people's code (Google Analytics and Maps, for instance).


Similarities:

1. Both methods result in a singleton;
2. Both result in accessible properties and methods;
3. Both methods help prevent cluttering the global namespace.


Differences:

1. The function method requires execution of its script, resulting in a longer loading time (which we can detect using the Chromium extension 'Speed Tracer');
2. The function method allows for naming variations between private and public members;
3. The members of the function singleton recognise each other, whereas those of the json singleton require the namespace prefix (therefore one could argue that the members of the json singleton aren't really its members which leads to the conclusion that the json method doesn't lead to a real singleton).

Thoughts?

Need problem solving?

Talk to me. Let's meet for coffee or over lunch. Mail me at “omegajunior at protonmail dot com”.