An object constructor is a function used to create multiple objects of the same type. This approach is particularly useful when you need to create many objects with similar properties and methods. The constructor function is defined with an uppercase first letter by convention. Open index.js to see the lesson.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
}
let person1 = new Person("Alice", 30);
let person2 = new Person("Bob", 25);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
person2.greet(); // Output: Hello, my name is Bob and I am 25 years old.