“Singleton” initializer in Javascript
Posted: July 19th, 2011 | Author: shesek | Filed under: Javascript, Web Development | Tags: javascript singleton, object initializer, singleton design pattern | No Comments »The nature of javascript makes it quite easy to have singleton-like behavior without actually using the singleton design pattern – simply define an object with some properties and use that. No need to do anything more than that, really – there’s no reason to create a prototyped function, create an instance and keep a reference to it when javascript gives you a much more natural and elegant solution.
For example:
var Foo = {
bar: 123,
a: function() { /* ... */ }
/* ... */
};
// Simply use Foo as a "singleton"
However, one thing that is missing from the singleton pattern is that the constructor is called only once, and only at the moment someone requests an instance, so it doesn’t run any code to initialize the object unless actually necessary.
Here’s my way of doing that in javascript:
var ObjectInitializer = function(object) {
var initialized = false;
return function() {
if (!initialized) {
object.initialize();
initialized = true;
}
return object;
};
};
To use that, simply add an initialize property on the object with the code to execute when the object is requested the first time, and pass it to ObjectInitializer, which’ll return an anonymous function that calls the initialize method the first time its accessed and returns the object, or simply returns the object otherwise.
Example:
var Foo = ObjectInitializer({
a: 3,
b: 2,
initialize: function() {
this.b += this.a;
},
increase: function() {
this.b++;
return this;
}
});
var foo = Foo();
alert(foo.b); // 5
foo.increase();
alert(foo.b); // 6
var bar = Foo();
alert(bar.increase().b); // 7
alert(Foo().increase().b); // 8