Javascript Patterns in ES6
1. Module Pattern
️ℹ️ Splits large file into multiple smaller reusable pieces.
Html
- adding the
type="module"
attribute to thescript
tags
Node
- Using the
.mjs
extension - Adding
"type": "module"
to yourpackage.json
✅ Encapsulation — values within a module are private by default
✅ Reusability — modules can be reused
2. Singelton Pattern
️ℹ️ ️️Allows class to have single instance only, which cannot be modified and is available globally.
✅ Memory — Reduced memory, setup for just one instance and reused
❌ Un-necessary — ES2015 Modules are singletons by default.
❌ Dependency Hiding — importing module may or may not be singleton
❌Global Scope Pollution — same as global variable can result in over-writing singleton value
3. Proxy Pattern
️ℹ️ Utilises proxy to intercept and control interaction stoa target object
✅ Control — adds functionality when interacting with objects
❌ Long handler execution — performance issues due to executing handles on every object
4. Observer Pattern
️ℹ️ Use observables to notify subscribers when an event occurs
✅ Separation of Concerns — observers can be decoupled from the observable object any time.
❌ Decreased performance — too many subscribers or complex observer handling can result in delay in notifying all subscribers
5. Factory Pattern
️ℹ️ Use a factory function in order to create objects
✅ DRY — multiple objects with same properties can be created
❌ Not really a pattern — function that returns an object
6. Prototype Pattern
️ℹ️ Share properties among many objects of the same type
✅ Memory efficient — common methods and properties moved to prototype.
❌ Readability — extending classes multiple times may result in difficulty in tracing the method and properties origin.