Understanding Constructor and Factory Functions in JavaScript
Constructor and factory functions are fundamental concepts in JavaScript for creating objects. They serve different purposes and have distinct advantages depending on the requirement.
Constructor Function
A constructor function is a function that is called with the new keyword. This invocation automatically creates a new object, sets the this keyword within the function to that object, and returns the object.
Factory Function
Unlike constructor functions, factory functions are called like regular functions. However, they are considered factories if they return a new instance of an object. This is done manually within the function.
When to Use Each Function Type
Constructor functions:
Factory functions:
Example
Here's an example demonstrating both function types:
// Constructor Function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } // Factory Function function createPerson(type) { switch (type) { case 'adult': return { name: 'John', age: 30 }; case 'child': return { name: 'Mary', age: 5 }; } }
In this example, the constructor function Person is used to create objects with prescribed name and age properties, and a greet method. The factory function createPerson allows for more flexibility by returning different person objects based on the type parameter.
The above is the detailed content of Constructor vs. Factory Functions: When Should You Use Each in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!