- Function factories can create objects with configurable properties, useful for generating standardized objects with specific defaults.
function createProductFactory(defaultCategory) {
return function(name, price) {
return {
name: name,
price: price,
category: defaultCategory,
getProductInfo() {
return `${this.name} costs $${this.price} and belongs to ${this.category} category.`;
}
};
};
}
const createElectronicsProduct = createProductFactory('Electronics');
const createClothingProduct = createProductFactory('Clothing');
const product1 = createElectronicsProduct('Laptop', 1000);
const product2 = createClothingProduct('T-shirt', 20);
console.log(product1.getProductInfo()); // Output: Laptop costs $1000 and belongs to Electronics category.
console.log(product2.getProductInfo()); // Output: T-shirt costs $20 and belongs to Clothing category.