What OOP flavour to use

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

What OOP flavour to use

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 function
const car = Car()

// Constructors and Classes
const car = new Car()

// OLOO
const 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 Classes
const car = new Car()

// OLOO
const 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.

// Class
class Car {
  constructor () {/* ... */}
  method () {/* ... */}
}

// Constructor
function Car () {/* ... */}
Car.prototype.method = function () {/* ... */}

In short, I like to keep things simple.