10 May 2008 · About 1 minute read

Javascript: Singleton Pattern in Javascript

At work, I have been developing a custom framework loosely based on my experience with the symfony and Propel. One of the requirements for the application under development is to store the application’s state both on the server and the client, so that information can be passed by means of AJAX requests.

To aid this process, each page controller PHP class has a corresponding Javascript class. In order to maintain state through the application, each class as a Singleton. With the help of Prototype, singleton classes are quick and easy to implement in Javascript:

First, declare the class itself using Prototype’s Class.create() method:

```javascriptPageController = Class.create({

/**

 * @type {integer}

 */

userId: null,

// ... more properties ...

/**

 * Constructor

 */

initialize: function()

{

// ...

},

/**

 * A method to do something...

 */

doSomething: function()

{

    console.log('doSomething()');

},

// ... more methods ...

});```

Once the class is created, we can declare a static instance of the class and a static method, getInstance(), that will be used to return the single instance of the class:

```javascript/**

*/

PageController.instance = null;

/**

*/

PageController.getInstance = function()

{

if(!PageController.instance)

    PageController.instance = new PageController()

return PageController.instance;

}```

With the class now declared, the singleton instance can be accessed in your application using the static getInstance() method:

javascriptPageController.getInstance().doSomething()

programming javascript design-patterns singleton
Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.