JavaScript classes are templates for creating objects. They encapsulate data with code to work on that data. Classes were introduced in ES6 and are a cleaner way to write constructor functions.
class Car {
constructor(brand) {
this.brand = brand;
}
drive() {
return `${this.brand} is driving!`;
}
}
const myCar = new Car("Toyota");
console.log(myCar.drive()); // "Toyota is driving!"
Use extends
to inherit from another class:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Bruno");
console.log(dog.speak()); // "Bruno barks."
super()
is used to call the parent class constructor:
class Employee {
constructor(name) {
this.name = name;
}
}
class Manager extends Employee {
constructor(name, dept) {
super(name); // Call parent constructor
this.dept = dept;
}
getDetails() {
return `${this.name} manages the ${this.dept} department.`;
}
}
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(newName) {
this._name = newName;
}
}
const p = new Person("Amit");
console.log(p.name); // Amit
p.name = "Sonia";
console.log(p.name); // Sonia
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!