You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+25-7Lines changed: 25 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -595,13 +595,31 @@
595
595
596
596
In this approach, create any function and apply the new operator to create object instances. This was the main way to do constructor-based OOP before ES6 classes.
597
597
598
-
```javascript
599
-
functionPerson(name) {
600
-
this.name= name;
601
-
this.age=21;
602
-
}
603
-
var object =newPerson("Sudheer");
604
-
```
598
+
```javascript
599
+
const Singleton = (function () {
600
+
let instance;
601
+
602
+
functioncreateInstance() {
603
+
return { name:"Sudheer" };
604
+
}
605
+
606
+
return {
607
+
getInstance:function () {
608
+
if (!instance) {
609
+
instance =createInstance();
610
+
}
611
+
return instance;
612
+
}
613
+
};
614
+
})();
615
+
616
+
// Usage
617
+
const obj1 = Singleton.getInstance();
618
+
const obj2 = Singleton.getInstance();
619
+
620
+
console.log(obj1 === obj2); // true
621
+
```
622
+
In modern JavaScript applications, singletons are commonly implemented using ES6 modules for their built-in caching behavior, or closures for encapsulated state management.
0 commit comments