Hereβs what I would choose:
- If I only need instances: Factory functions
- If I need Prototypal Delegation: Classes
I would not use Constructor functions or OLOO.
Why Factory Functions
First. Factory functions are easy to create. They are also easy to understand. Beginners and experts alike can see what they do at a glance.
function Human(firstName, lastName) { return { firstName, lastName, }}Second. Factory functions are easy to use. You run the function normally. You donβt need new. You also donβt need to run init.
// Factory functionconst car = Car()
// Constructors and Classesconst car = new Car()
// OLOOconst car = Object.create(Car).init()Third. Factory Functions can use Object composition easily. This lets us create flexible programs from the get-go.
Fourth. We can always refactor Factory Functions to Classes if we need Prototypal Delegation later.
Why Classes for Prototypal Delegation
First. Classes are easier to use compared to OLOO. You write new, but you donβt need Object.create(x).init(y)
// Constructors and Classesconst car = new Car()
// OLOOconst car = Object.create(Car).init()Second. Itβs easier to write Classes compared to Constructors. I donβt need an extra prototype declaration to add methods into the Prototype Chain.
// Classclass Car { constructor() { /* ... */ } method() { /* ... */ }}
// Constructorfunction Car() { /* ... */}Car.prototype.method = function () { /* ... */}In short, I like to keep things simple.
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson