Object Constructors in JavaScript
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.
Defining an Object Constructor
this
assigns properties to the new object.new
creates a new object, sets its prototype, and bindsthis
to it.- Methods can be defined inside the constructor (per instance) or on the prototype (shared across instances).
function ConstructorName(param1, param2) {
this.property1 = param1;
this.property2 = param2;
// Methods can be defined here or on the prototype
}
Creating Objects with Constructors
When a constructor is called with new
:
- A new empty object is created.
- The object’s prototype is set to the constructor’s
prototype
property. this
is bound to the new object.- The new object is returned automatically (unless another object is explicitly returned).
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
Adding Methods to the Prototype
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