Sometimes we need a blueprint to create many objects of the same type. For example, if you are building a game with thousands of enemies, you need a single template to define what an "Enemy" looks like. In JavaScript, this blueprint is called an Object Constructor.
An object constructor is a function. It is considered good practice to name constructor
functions with an upper-case first letter (e.g., Person instead of
person).
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Objects of the same type are created by calling the constructor function with the
new keyword.
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
console.log(myFather.age); // 50
In a constructor function, this does not have a value yet. It is a substitute
for the new object. The value of this will become the new
object when it is created using the new keyword.
You can add new properties or methods to a single object instance at any time without affecting the other instances or the original constructor.
myFather.nationality = "English";
// Only myFather has this property now. myMother does NOT.
Your constructor can also define methods that every instance will share:
function Person(first, last) {
this.firstName = first;
this.lastName = last;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
JavaScript has built-in constructors for native objects:
new Object() — Creates a new Objectnew String() — Creates a new String (Not recommended)new Number() — Creates a new Number (Not recommended)new Array() — Creates a new Arraynew Date() — Creates a new Datenew keyword to create an instancethis keyword inside a constructor refers to the new
object being created