/ Published in: JavaScript
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.
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var Singleton = (function () { var instantiated; function init() { // singleton here return { publicMethod: function () { console.log('hello world'); }, publicProperty: 'test' }; } return { getInstance: function () { if (!instantiated) { instantiated = init(); } return instantiated; } }; })(); // calling public methods is then as easy as: Singleton.getInstance().publicMethod();