JavaScript OOPs Classes

JavaScript Classes provide a way to create objects and implement inheritance in a more structured and readable manner. Classes are a blueprint for creating objects with shared properties and methods, making it easier to organize code and implement Object-Oriented Programming (OOP) principles.

Key Features of JavaScript Classes:

Basic Syntax of JavaScript Class

A JavaScript class is defined using the class keyword. Inside the class, you can define a constructor and methods:

Syntax


class MyClass 
{
 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.");
    }
}                
                        

Example: Defining and Using a Class

The following example defines a simple class called Person and creates an instance of it:

Example

<script type="text/javascript">
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();  // Output: Hello, my name is Alice and I am 30 years old.
</script>

Output

The console will output: Hello, my name is Alice and I am 30 years old.

Explanation of Code:

Inheritance in JavaScript Classes

In JavaScript, one class can inherit properties and methods from another class using the extends keyword. This allows us to create a class hierarchy and reuse code efficiently.

Example: Inheritance in JavaScript Classes

Example


<script type="text/javascript">
class Animal 
{
    constructor(name)
    {
        this.name = name;
    }
            
    speak() 
    {
    console.log(this.name + " makes a sound.");
    }
}
            
class Dog extends Animal 
{
    constructor(name, breed) 
    {
       super(name);  // Call the parent class's constructor
       this.breed = breed;
    }
            
    speak() 
    {
        console.log(this.name + " barks.");
    }
}
            
let dog1 = new Dog("Max", "Golden Retriever");
    dog1.speak();  // Output: Max barks.
</script>

Output

The console will output: Max barks.

Explanation of Code:

Static Methods in JavaScript Classes

Static methods are methods that are called on the class itself, not on instances of the class. They are defined using the static keyword.

Example: Static Method in JavaScript Class

Example


<script type="text/javascript">
class MathUtility
{
    static add(a, b) 
    {
     return a + b;
    }
            
    static multiply(a, b) 
    {
     return a * b;
    }
}
            
console.log(MathUtility.add(5, 3));  
console.log(MathUtility.multiply(5, 3));  
</script>

Output

The console will output: 8
15

Explanation of Code: