A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so without the new keyword, it's a factory function.
Here's an example of factory function code:
// Factory Function
function createCircle(radius) {
return {
radius,
draw: function() {
console.log('draw');
}
};
}
const circle = createCircle(1);
circle.draw();
Constructor functions technically are regular functions. There are two conventions though:
The regular {...}
syntax allows to create one object. But often we need to create many similar objects, like multiple users or menu items and so on.
That can be done using constructor functions and the new
operator.
new
operator.For instance:
// Constructor Function
function Circle(radius) {
this.radius = radius;
this.draw = function() {
console.log('draw');
}
}
const another = new Circle(1);