Posted By

peta on 10/13/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

yeco


3 ways of implementing the Singleton pattern in JavaScript


 / Published in: JavaScript
 

  1. // WAY 1 - Instantiating an anonymous function
  2. var MySingleton = new (new MyClass(args));
  3.  
  4. // WAY 2 - Using an instance manager
  5. var getMySingleton = (function(options) {
  6. function MyClass(args) {}
  7.  
  8. var singleton;
  9. return function(args) {
  10. return singleton ? singleton : singleton = new MyClass(args);
  11. }
  12. })();
  13.  
  14. // WAY 3 - The simple way
  15. var MySingleton = {
  16. prop: "foo",
  17. method: function() {},
  18. ...
  19. };

Report this snippet  

You need to login to post a comment.