JavaScript Object Constructors
JavaScript object constructors are special functions used to create and initialize objects. These constructors define the properties and methods that instances of the object will have.
1. Constructor Functions
A constructor function is a regular function that is used to create objects. Constructor functions are typically capitalized to distinguish them from regular functions.
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = new Person('Alice', 25);
console.log(alice); // Person { name: 'Alice', age: 25 }
2. ES6 Classes
ES6 introduced class syntax as a more modern way to define constructor functions. Classes are syntactical sugar over JavaScript’s existing prototype-based inheritance.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const alice = new Person('Alice', 25);
console.log(alice); // Person { name: 'Alice', age: 25 }
3. Inheritance with ES6 Classes
ES6 classes support inheritance using the extends
keyword. This allows one class to inherit the properties and methods of another class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
class Student extends Person {
constructor(name, age, studentId) {
super(name, age);
this.studentId = studentId;
}
showId() {
console.log(`Student ID: ${this.studentId}`);
}
}
const bob = new Student('Bob', 22, 'S123');
bob.greet(); // Hello, my name is Bob
bob.showId(); // Student ID: S123
4. Static Methods
Static methods are called on the class itself, not on instances of the class. They are defined with the static
keyword.
class MathHelper {
static add(a, b) {
return a + b;
}
}
console.log(MathHelper.add(5, 10)); // 15
5. Factory Functions
Factory functions are functions that return a new object each time they are called. They are a common way to create objects without using the new
keyword.
function createPerson(name, age) {
return {
name: name,
age: age,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
}
const charlie = createPerson('Charlie', 30);
charlie.greet(); // Hello, my name is Charlie