Javascript Static Singleton
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.
jsfiddle link: http://jsfiddle.net/timsommer/thxn4/
var SingletonTester = (function () {
//This is the actual singleton instance
function Singleton() {
this.name = "Singleton";
this.pointX = 16;
}
// this is our instance holder
var instance;
// this is an emulation of static variables and methods
var _static = {
name: 'SingletonTester',
// This is a method for getting an instance
// It returns the same instance of the singleton object
getInstance: function () {
if (instance === undefined) {
instance = new Singleton();
}
return instance;
}
};
return _static;
})();
//getInstance method is the only method we can call on the returned _static object
var singletonTest = SingletonTester.getInstance();
console.log(singletonTest.pointX); // outputs 16
singletonTest.pointX = 15;
console.log(singletonTest.pointX); // outputs 15Written by Tim Sommer
Related protips
1 Response
Hi, I just upated your example a bit (corrected docs, shortened code, output in textarea instead of console):
http://jsfiddle.net/maxhq/Ltnq1k6j/
Regards,
maxhq
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Design patterns
Authors
pdabrowski
11.89K
endel
3.878K
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#