In JavaScript this pattern restricts instantiation of an object to a single reference thus reducing its memory footprint and allowing a "delayed" initialization on an as-needed basis. This isn't too common among JavaScript projects.
Here is how a singleton pattern can be implemented with JavaScript
- Easiest way is using object literals
var singletonObject ={ method1:function(){ }, method2:function(){ } }
- Little more organized way using closures
when we access the object it can be done like,var singletonObject = (function(){ var instance; function initiateInstance(){ var object = new Object("my Object"); return object; } return{ getSingletonInstance:function(){ if(!instance){ instance=initiateInstance(); } return instance; } } })();
var instance1=singletonObject.getSingletonInstance(); var instance2=singletonObject.getSingletonInstance(); //instance1===instance2
No comments:
Post a Comment