3 ways of implementing the Singleton pattern in JavaScript


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.