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 hidden or 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
However, I use those mostly for plain data objects, instead of behavior, and then define behaviors separately:
This style is called functional programming. I wrote a whole book about it.