Last active
November 17, 2024 01:09
-
-
Save ericelliott/ad2c5dc46fca6bf1b18a422818a998eb to your computer and use it in GitHub Desktop.
Class, Constructor, Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
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
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.