-
Notifications
You must be signed in to change notification settings - Fork 0
36 Factory Function
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
A factory function is a function that returns a new object.
- The object is usually created using the
newoperator and a constructor function - but the factory function abstracts this process and provides a more flexible and reusable way to create objects.
- In this example
createPerson()function is a factory function - Factory functions are useful for creating objects with a similar structure, as they provide a reusable way.
function createPerson(name, age) {
return {
name: name,
age: age,
};
}
const person1 = createPerson("John", 30);
const person2 = createPerson("Jane", 25);
console.log(person1);
console.log(person2);- Here
calculateTaxis a factory function that holds reusable logic. - When the
createTaxCalculatoris invoked it creates anewfunction ofcalculateTaxand returns the same.
function createTaxCalculator(tax) {
function calculateTax(amount) {
return amount * tax;
}
return calculateTax;
}
const calculateVatAmount = createTaxCalculator(0.19);
const calculateIncomeTax = createTaxCalculator(0.23);
console.log(calculateVatAmount(100));
console.log(calculateIncomeTax(200));- The
createPersonfactory function takes name and age as arguments and returns an object with properties name, age, and a greet method. - Each time the createPerson function is called, a new object is created with the specified properties and behavior.
- Factory functions encapsulate object creation logic, allowing us to define default values, apply data validation etc.
- It's flexible and expressive approach to create objects compared to constructor functions
- Especially when the creation process involves complexity or customization.
- Factory functions can be combined with other design patterns, such as the module pattern,
- to create powerful and modular code structures in JavaScript.
function createPerson(name, age) {
return {
name: name,
age: age,
greet: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
}
const person1 = createPerson('John', 25);
const person2 = createPerson('Alice', 30);
person1.greet(); // Output: Hello, my name is John and I'm 25 years old.
person2.greet(); // Output: Hello, my name is Alice and I'm 30 years old.- A factory function is a function that is designed to create and return objects.
- It is a pattern that allows you to encapsulate object creation logic and customize the properties or behavior of the objects being created.
- The main purpose of a factory function is to provide a convenient way to create multiple instances of similar objects without explicitly using the new keyword or constructor functions.