Object Factory
If we need to create many similar objects (like users or products), we use constructor functions.
Syntax
- The function name is capitalized.
- It is called using the
newoperator.
function User(name) {
// this = {}; (implicitly)
this.name = name;
this.isAdmin = false;
// return this; (implicitly)
}
let user = new User("Jack");
What happens with " new " ?
- A new empty object is created and assigned to
this. - The function body executes (usually modifying
this). - The value of
thisis returned.
Tip
You can pass any parameters into a constructor. This is a great way to encapsulate the logic for creating complex objects.