Lesson 30 +15 XP

Object Constructors

Object Constructors

A constructor function is a template for creating many similar objects.

Why constructors?

Writing each object by hand gets repetitive. A constructor lets you create unlimited objects with the same shape:

const person1 = { name: "Ada", age: 36 };
const person2 = { name: "Bob", age: 40 };
// and on and on...

Create a constructor

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Create objects with new

const ada = new Person("Ada", 36);
const bob = new Person("Bob", 40);

How it works

  • The function name starts with a capital letter by convention.
  • new creates a new empty object.
  • this refers to the new object.
  • Properties are assigned onto it.

Add methods to a constructor

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.describe = function() {
    return this.name + " is " + this.age;
  };
}

TL;DR

  • A constructor function is a template for objects.
  • Use new to create objects from it.
  • this inside the constructor refers to the new object.
  • Constructor names start with a capital letter.