This Javascript program demonstrates a singleton design pattern. The constructor function prevents multiple instances from being created. The static GetInstance() provides global access to the singleton instance.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="Singleton.js"></script> </head> <body onload="Initialize()"> </body> </html>
class CSingleton {
// The singleton instance, a private class memeber.
static #sqInstance;
constructor() {
if (!CSingleton.#sqInstance) {
CSingleton.#sqInstance = this;
}
return CSingleton.#sqInstance;
}
static GetInstance() {
if (!CSingleton.#sqInstance) {
CSingleton.#sqInstance = new CSingleton();
}
return CSingleton.#sqInstance;
}
}
function Initialize() {
var qSingleton1 = CSingleton.GetInstance();
var qSingleton2 = new CSingleton();
var qSingleton3 = new CSingleton();
var qSingleton4 = CSingleton.GetInstance();
document.writeln("Instances are equal: " + (qSingleton1 === qSingleton2)+"<br />");
document.writeln("Instances are equal: " + (qSingleton1 === qSingleton3)+"<br />");
document.writeln("Instances are equal: " + (qSingleton1 === qSingleton4)+"<br />");
}
© 20072025 XoaX.net LLC. All rights reserved.