Creating singleton in javascript
1 min readSep 9, 2019
Singleton pattern is used to make sure only one object of class is created across the whole application.
In this article i am going to describe how we can achieve singleton in javascript es6. There are multiple ways to achieve this but the one which i am going to write is very simple & clean.
Check out the below code -
class Person {
constructor() {
if (this.instance) {
return this.instance;
} else {
Person.prototype.instance = this;
}
} getName() {
console.log(this.name);
} setName(val) {
this.name = val;
}
}const person1 = new Person();
person1.setName("ujjwal");
person1.getName(); // value will be ujjwalconst person2 = new Person();
person2.setName("ujjwal gupta");// here we are trying to get value from person1 instance but since the class Person is singleton. It will return value from last set.person1.getName(); // value will be again ujjwal gupta
Here we are using prototype to ensure - we have only one value of instance for whole class.
Hope you find this article useful. Thanks for reading guys!.