Now, we will discuss the syntax of singleton’s class, and the singleton’s function one by one. Also, we will discuss how to access their instances in detail.
Singleton method in JavaScript
There are many methods that can be used to declare a singleton, a very basic way of declaring a singleton is as:
fname: 'joe',
lname: 'clarke',
simpleMethod: function () {
return this.fname + ' ' + this.lname;
},
};
console.log("simpleMethod : ",SingletonExample.simplemethod());
The output of this code will be:
Singleton class in JavaScript
Implementing a singleton class in JavaScript is not very complex, the basic syntax of singleton class will be:
class employee {
constructor(id, name, city, designation) {
if (!check_instance) {
this.id=id;
this.name=name;
this.city=city;
this.designation=designation;
check_instance=this;
}
else
{
return check_instance;
}
}
}
const emp1 = new employee(1, 'Roman', 'Paris', 'Manager');
console.log("First employee : ",emp1);
Here, we created a class named employee and a variable named check_instance with a null value. Inside the class, we use if-statement to check if the instance is null or not and if the instance is null then if-statement will be executed else it would simply return the ‘check_instance’.
Output:
Now, create another instance and check what will happen when we create two instances of a singleton class.
For this purpose simply extend the above code a little bit and create another instance of the class and assign some properties to it:
class employee {
constructor(id, name, city, designation) {
if (!check_instance) {
this.id=id;
this.name=name;
this.city=city;
this.designation=designation;
check_instance=this;
}
else
{
return check_instance;
}
}
}
const emp1 = new employee(1, 'Roman', 'Paris', 'Manager');
const emp2 = new employee(2, 'Seth', ' New York', 'Director');
console.log("First employee : ",emp1);
console.log("Second employee : ",emp2);
Now implement the above code and observe whether a new employee is created or not:
Output:
The output will verify that it didn’t create the second instance instead it returns the same instance again:
Conclusion
Singletons are one of the easiest design patterns to understand. Singleton patterns are the way of creating a single object that can be shared among a number of different resources throughout the application without recreating those objects. If someone calls the constructor of a class it will return the same instance again and again.