Clean • Professional
An object constructor is a function designed to create and initialize objects when called with the new keyword. It defines a template for objects, specifying their properties and methods. Constructors are particularly useful for creating multiple instances of objects with similar characteristics.
this assigns properties to the new object.new creates a new object, sets its prototype, and binds this to it.function ConstructorName(param1, param2) {
this.property1 = param1;
this.property2 = param2;
// Methods can be defined here or on the prototype
}
When a constructor is called with new:
prototype property.this is bound to the new object.function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
}
const john = new Person("John", 30);
const alice = new Person("Alice", 25);
console.log(john.name); // "John"
john.greet(); // "Hello, I'm John"
console.log(alice.age); // 25
Defining methods inside the constructor creates a new function for each instance, consuming more memory.
To share methods across all instances, define them on the constructor’s prototype:
function Person(name, age) {
this.name = name;
this.age = age;
}
// Add method to prototype
Person.prototype.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
const john = new Person("John", 30);
const alice = new Person("Alice", 25);
john.greet(); // "Hello, I'm John"
alice.greet(); // "Hello, I'm Alice"
// Check if the method is shared
console.log(john.greet === alice.greet); // trueÂ