A class in JavaScript is a template for creating objects. It allows us to define properties (variables) and methods (functions) inside a structured format.
JavaScript classes were introduced in ES6 and provide a cleaner way to create and manage objects compared to traditional constructor functions.
class ClassName {
constructor() {
// Initialize properties
}
methodName() {
// Define a method
}
}
class Person {
constructor(name, age) {
this.name = name; // Property
this.age = age;
}
greet() { // Method
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Creating an object
let person1 = new Person("John", 25);
person1.greet();
๐ Output: "Hello, my name is John and I am 25 years old."
Person
class defines a constructor to initialize properties.greet
method prints a message.person1
is an object created from the Person
class.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
start() {
console.log(`${this.brand} ${this.model} is starting...`);
}
stop() {
console.log(`${this.brand} ${this.model} is stopping.`);
}
}
// Creating an object
let myCar = new Car("Toyota", "Corolla");
myCar.start();
myCar.stop();
๐ Output:
Toyota Corolla is starting...
Toyota Corolla is stopping.
Car
class has two methods: start()
and stop()
.myCar
and call its methods.
We can extend a class to create a child class.
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks.`);
}
}
let myDog = new Dog("Buddy");
myDog.makeSound(); // Inherited method
myDog.bark(); // Child class method
๐ Output:
Buddy makes a sound.
Buddy barks.
Dog
class inherits from Animal
.makeSound()
and bark()
methods.
โ Encapsulation: Keeps data and functions together.
โ Reusability: Easily create multiple objects from a single class.
โ Inheritance: Allows child classes to inherit properties and methods.
โ Better Readability: Cleaner structure compared to traditional functions.
@asadmukhtar