2Minutes: Factory Functions In JavaScript
What is Factory Functions in JavaScript?
A Factory Function is simply a function that returns an object. You can think of it as a blueprint for creating objects with the same properties and methods. It’s similar to classes, but instead of using the class keyword and new, it just returns an object. Look at the following:
function Person(name, age) {
return {
name,
age,
sayHi: () => {
console.log(`Hi ! I'm ${name}. I'm ${age} years old !`);
}
};
}
const khalid = Person("Khalid", 25);
khalid.sayHi(); // Output: Hi ! I'm Khalid. I'm 25 years old.That’s pretty much what Factory Functions are.
That’s 2Minutes, see you in the next one !
Sources
https://www.geeksforgeeks.org/javascript/what-are-factory-functions-in-javascript
https://dev.to/snevy1/classes-vs-factory-functions-in-javascript-4fjn