Loading lessons...
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.
newcreates a new empty object.thisrefers 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
newto create objects from it. thisinside the constructor refers to the new object.- Constructor names start with a capital letter.