5.3 Contructor Function
Factory functions are not the only way to build objects. The other classic pattern in JavaScript is the constructor function. Like a factory, it is a function whose job is to produce an object, but the syntax and conventions are different.
Naming conventions
- Factory functions use camelCase — like
createCircle. - Constructor functions use PascalCase — like
Circle. Other JavaScript developers will assume PascalCase functions are constructors.
function Circle(radius) {
this.radius = radius;
this.draw = function () {
console.log("draw");
};
}
const circle = new Circle(1);
circle.draw();
Instead of returning an object literal, we assign properties on this. The this keyword is a reference to the object that is currently executing this piece of code. Because objects in JavaScript are dynamic, we can add properties to them at any time — including the radius property and the draw method.
The magic happens when we call Circle with the new operator. Three things happen behind the scenes:
newcreates a new empty JavaScript object.- It binds
thisinside the function to that new empty object. - After the function runs,
newreturns that object.
If you forget the new operator, this defaults to the global object (window in the browser), which is almost never what you want. Factory functions and constructor functions are both equally valid ways to create objects — pick the one your team is most comfortable with. Constructor functions tend to feel more familiar to developers coming from class-based languages like C# or Java.