Object Factory

If we need to create many similar objects (like users or products), we use constructor functions.

Syntax

  1. The function name is capitalized.
  2. It is called using the new operator.
function User(name) {
  // this = {}; (implicitly)
  this.name = name;
  this.isAdmin = false;
  // return this; (implicitly)
}

let user = new User("Jack");

What happens with " new " ?

  1. A new empty object is created and assigned to this.
  2. The function body executes (usually modifying this).
  3. The value of this is returned.
Tip

You can pass any parameters into a constructor. This is a great way to encapsulate the logic for creating complex objects.