Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Created December 14, 2009 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slashdotdash/256147 to your computer and use it in GitHub Desktop.
Save slashdotdash/256147 to your computer and use it in GitHub Desktop.
JavaScript Singleton
// http://prototyp.ical.ly/index.php/2007/03/01/javascript-design-patterns-1-the-singleton/
// http://books.google.co.uk/books?id=za3vlnlWxb0C&printsec=frontcover&source=gbs_navlinks_s#v=onepage&q=singleton&f=false
var mySingleton = function()
{
/* private attributes */
var _created = new Date();
/* private methods */
var _calculateAge = function()
{
return new Date().getTime() - _created.getTime();
}
return {
/* public attributes*/
name: 'M.Y. Singleton',
/* public methods */
tellBirthday:function()
{
alert('Hello, my name is ' + this.name + ' and I was created on ' + _created.toLocaleString() +');
},
tellAge:function()
{
alert('I am '+_calculateAge()+'ms old.');
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment