Implementing the singleton pattern in JavaScript

Implementing the singleton pattern in JavaScript requires a basic knowledge of JavaScript class instantiation. For example, given the following code:

function A {
  this.property = 'Foo';
}

you cannot write something like this:

alert(A.property); // error

because the A class has not been instantiated yet through the new operator. Instead, you have to create a self-instantiating class, like this:

var A = new function() {
  this.property = 'Foo';
}

Now everything works just fine:

alert(A.property); // 'Foo'

Leave a Reply

Note: Only a member of this blog may post a comment.