Object constructors are used to create blueprints for an object. They are a more dynamic way of create objects and are very useful when you create many objects of the same type. For example, you can have a Person Object constructor that can be used as a blueprint to create many other objects with name, birthYear and gender properties.
The following creates a person object constructor with properties of name, birthYear ,company and gender.
//Create a `Person` object constructor
function Person(name,birthYear,company,gender){
this.name = name;
this.birthYear = birthYear;
this.company = company;
this.gender = gender;
}
After creating the person object constructor, we can use it to create other `people objects`.
//Create a `Person` object constructor
function Person(name,birthYear,company,gender){
this.name = name;
this.birthYear = birthYear;
this.company = company;
this.gender = gender;
}
// Create a new Person object `mark`.
const mark = new Person('Mark',1984,'Facebook','male');
Adding a `method` to the existing person object `mark` is done outside the person object constructor
//Create a `Person` object constructor
function Person(name,birthYear,company,gender){
this.name = name;
this.birthYear = birthYear;
this.company = company;
this.gender = gender;
}
// Create a new Person object `mark`.
const mark = new Person('Mark',34,'Facebook','male');
// Add a method to the existing Person object `mark`
mark.greeting = () =>{
console.log(`Hi my name is ${mark.name} and I am CEO of Facebook`); // this greeting is unique to mark.
}
Using the Person object constructor we have create above, we can create similar objects using the Person object blueprint.
// Create a new Person object `elon`.
const elon = new Person('Elon',1971,'SpaceX','male');
// Create a new Person object `bill`.
const bill = new Person('Bill',1955,'Microsoft','male');
// Create a new Person object `marissa`.
const bill = new Person('Marissa',1975,'Yahoo','female');