ES6 (ECMAScript 2015) introduced a new syntax for creating objects and dealing with inheritance, known as classes. Although JavaScript has always been an object-oriented language, ES6 classes make it easier to understand and write object-oriented code.
A class in JavaScript is created using the class keyword, followed by the class name. Inside the class, we define a constructor method and other methods.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person1 = new Person('Alice', 30);
person1.greet(); // Hello, my name is Alice and I am 30 years old.
A constructor is a special method for creating and initializing an object created with a class. It is called when a new instance of the class is created.
The constructor method is defined with the keyword constructor. It can accept parameters and is used to set up the properties of the object.
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
displayInfo() {
console.log(`${this.brand} ${this.model} (${this.year})`);
}
}
let myCar = new Car('Toyota', 'Corolla', 2020);
myCar.displayInfo(); // Toyota Corolla (2020)
Inheritance is a fundamental principle of object-oriented programming. It allows a class to extend another class, inheriting its properties and methods while adding new ones or modifying existing ones.
The extends keyword is used to create a subclass (child class) that inherits from a superclass (parent class).
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the constructor of the parent class
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
let myDog = new Dog('Rex', 'Labrador');
myDog.speak(); // Rex barks.
In the above example, the speak method is overridden in the Dog class to provide a specific implementation for dogs.
Static methods and properties belong to the class itself, rather than to instances of the class. They are often used for utility functions or constants.
Static methods are defined using the static keyword. They can be called on the class itself, not on instances of the class.
class MathUtilities {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathUtilities.add(2, 3)); // 5
console.log(MathUtilities.multiply(4, 5)); // 20
Static properties are also defined using the static keyword and can be accessed on the class itself.