Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active August 28, 2023 18:18
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ericelliott/ad2c5dc46fca6bf1b18a422818a998eb to your computer and use it in GitHub Desktop.
Save ericelliott/ad2c5dc46fca6bf1b18a422818a998eb to your computer and use it in GitHub Desktop.
Class, Constructor, Factory
// class
class ClassCar {
drive () {
console.log('Vroom!');
}
}
const car1 = new ClassCar();
car1.drive();
// constructor
function ConstructorCar () {}
ConstructorCar.prototype.drive = function () {
console.log('Vroom!');
};
const car2 = new ConstructorCar();
car2.drive();
// factory
const proto = {
drive () {
console.log('Vroom!');
}
};
const factoryCar = () => Object.create(proto);
const car3 = factoryCar();
car3.drive();
@brandonkoopa
Copy link

Thank you for the clear differences, it actually helps a lot. Cheers!

@etiennejcharles
Copy link

I gotta say the same man, thanks Eric, really!

@praveeno
Copy link

praveeno commented May 8, 2018

But when to use what ?

@sfratczak
Copy link

Hey @ericelliott, it seems you're unnecessarily using console.log() after instantiating new ClassCar and ConstructorCar and calling their drive method (it already has a console.log() in it.)
Noticed this when reading your JavaScript Factory Functions vs Constructor Functions vs Classes post on Medium.

@ericelliott
Copy link
Author

ericelliott commented Aug 28, 2023

But when to use what ?

I don't use any of these in real applications most of the time. Instead, I use factory functions without prototype links most of the time:

const noProtoCar = () => ({
  drive: () => console.log('Vroom!')
});

const car = noProtoCar();
car.drive(); // "Vroom!"

However, I use those mostly for plain data objects, instead of behavior, and then define behaviors separately:

const createVehicle = ({wheels}) => ({
  sound = 'Vroom!',
} = {}) => ({
  sound,
  wheels,
});

const createCar = createVehicle({ wheels: 4 });

// Define behaviors as separate functions - makes them more reusable across many different types of objects.
const drive = ({ sound }) => console.log(sound);

const car = createCar();
drive(car); // Vroom!

// Now we can use it with motorcycles too!
const createMotorcycle = createVehicle({ wheels: 2 });

const motorcycle = createMotorcycle({ sound: 'Brrrrrrrrrrrrm!' });
drive(motorcycle); // Brrrrrrrrrrrrm!

This style is called functional programming. I wrote a whole book about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment