Skip to content

Commit 2a85e90

Browse files
committed
Modify singleton behavior
1 parent 85f827d commit 2a85e90

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

README.md

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -595,13 +595,31 @@
595595

596596
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.
597597

598-
```javascript
599-
function Person(name) {
600-
this.name = name;
601-
this.age = 21;
602-
}
603-
var object = new Person("Sudheer");
604-
```
598+
```javascript
599+
const Singleton = (function () {
600+
let instance;
601+
602+
function createInstance() {
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.
605623

606624
5. **Function constructor with prototype:**
607625

0 commit comments

Comments
 (0)