<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Creating a singleton Class in ES6</h1>
<span id="txt"></span>
<script>
let txt = document.getElementById('txt');
let sInstance = null;
class SingletonExample {
constructor() {
if (!sInstance) {
sInstance = this;
txt.textContent = "Singleton Class Created!";
} else {
txt.innerHTML += "<br>Whoopsie, you're only allowed one instance of this Class!";
}
return sInstance;
}
}
let singletonExample = new SingletonExample();
let singletonExample2 = new SingletonExample();
//test
txt.innerHTML += '<br>' + (singletonExample === singletonExample2);
txt.innerHTML += '<br>' + (singletonExample === sInstance);
txt.innerHTML += '<br>' + (singletonExample2 === sInstance);
singletonExample['test123'] = 'dfdfdf';
txt.innerHTML += '<br>' + (singletonExample2['test123']);
</script>
</body>
</html>