Javascript Singleton Pattern


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

In conventional software engineering, the singleton pattern can be implemented by
creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.


Copy this code and paste it in your HTML
  1. var Singleton = (function () {
  2. var instantiated;
  3. function init() {
  4. // singleton here
  5. return {
  6. publicMethod: function () {
  7. console.log('hello world');
  8. },
  9. publicProperty: 'test'
  10. };
  11. }
  12. return {
  13. getInstance: function () {
  14. if (!instantiated) {
  15. instantiated = init();
  16. }
  17. return instantiated;
  18. }
  19. };
  20. })();
  21.  
  22. // calling public methods is then as easy as:
  23. Singleton.getInstance().publicMethod();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.