JavaScript Class Extends

What is Class in JavaScript?

In JavaScript, classes serve as blueprints for generating objects, enabling the encapsulation of both data and functionality for manipulation. This concept belongs to object-oriented programming and was introduced with ECMAScript 2015, commonly referred to as ES6. Utilizing classes in JavaScript allows developers to establish templates that facilitate object creation. While these classes are fundamentally based on prototypes, they also incorporate specific syntax and semantics that distinguish them within the JavaScript language.

Syntax

The syntax of class in JavaScript is as follows:

In JavaScript, to define a class, you must utilize the keyword class along with a method referred to as constructor.

Example

class ClassName() {
constructor(){
….}
};

What is Class Extend in JavaScript?

In JavaScript, the class extends a specific keyword that enables us to generate a subclass from an existing class, often referred to as the parent class. By utilizing this subclass, we can inherit all the attributes and methods of its parent class. Inheritance is a fundamental concept in Object-Oriented Programming (OOP) within JavaScript, which facilitates code reusability. This allows us to leverage the properties and methods of an already established class when developing a new class.

By utilizing the extends keyword in JavaScript, it becomes possible to formulate both class declarations and expressions. This allows us to establish a class that functions as a subclass of an existing class, effectively serving as the prototype for the derived child class.

Syntax

Example

class ParentClass {}
class ChildClass extends ParentClass {}
Object.getPrototypeOf( ChildClass );
class ParentClass {}

These derived classes obtain the attributes and functions of the superclass. This allows you to enhance the fundamental capabilities of a class to cater to a more specialized function without burdening the parent class to accommodate every conceivable scenario or duplicating code that fulfills a comparable role.

Example

Let’s consider an illustration that demonstrates the use of the extend keyword in JavaScript:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>extends in JavaScript</title>
</head>
<body style="text-align: center;">
    <script>
        class extAnimal{
            constructor(name){
                this.name= name;
            }
            animalSize(){
                document.write(`Elephant is bigger ${this.name}`)
            }
        }
        class Jungle extends extAnimal {
        }
        let wildAnimal = new Jungle('than Lion');
        wildAnimal.animalSize();
    </script>
</body>
</html>

Output:

Explanation

In the aforementioned illustration, the Jungle class derives all the methods and attributes from the extAnimal class. As a result, the animalSize function along with the name attribute will be present within the Jungle class. Following this, we created an instance of the wildAnimal object and utilized it to invoke the animalSize method belonging to the Jungle class.

Example 2

Example

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>"extends" keyword in JavaScript</title>
</head>
<body style="text-align:center">
   <script>
      class Animal {
         constructor(name) {
            this.name = name;
         }
         clawSize() {
            document.write(`Bear has ${this.name}`);
         }
      } 
      class Jungle extends Animal {
         constructor(name) {
            document.write("Created jungle as class"+"<br>");
            super(name);
         }
      }
      let wildAnimal = new Jungle('long claws');
      wildAnimal.clawSize();
   </script>
</body>
</html>

Output:

Explanation

In the preceding illustration, it is evident that the Jungle class functions as a subclass of the Animal class. As a result, each time the Jungle class's constructor is called, it simultaneously triggers the constructor of the Animal class, thereby providing it with a name attribute.

Example 3

Example

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>"extends" keyword in JavaScript </title>
</head>
<body style="text-align:center">
   <script>
      class Animal {
         constructor(name) {
            this.name = name;
            this.behavior = "aggressive";
         }
         overrideMethod() {
            document.write();(`Hello ${this.name}.`);
         }
      }
      class Jungle extends Animal {
         constructor(name) {
            super(name);
            this.behavior = 'Wild';
         }
         overrideMethod() {
            document.write(`Loins are very ${this.name}`);
            document.write('behavior: ' + this.behavior);
         }
      }
      let y = new Jungle('Aggressive'+'<br>');
      y.overrideMethod();
   </script>
</body>
</html>

Output:

Explanation

In the preceding example, when a method or property within a subclass shares its name with a method or property from its superclass, the method or property defined in the subclass will take precedence. This functionality is referred to as method overriding.

In this specific case, both the Animal class and the child Jungle class have the behavior property and the overrideMethod function. In this context, the overrideMethod function and the behavior property are overridden by the Jungle class.

How does class extend work in JavaScript?

Some points will show how JavaScript works:

  • The extends keywords in JavaScript is used to create a child class that inherits properties and methods from a parent class. It is a form of code reusability.
  • In JavaScript, the child class also known as the derived class which automatically inherits all the methods and properties of the parent class also known as the base class.
  • The child class can also override or extend the methods and properties inherited from the parent class.
  • In JavaScript, the super keyword is used to access and call the constructor of the parent class from the child class.
  • Multiple inheritance is not directly supported in JavaScript. However, we can use techniques like mixins to achieve similar results.
  • Understanding extends is crucial for object-oriented programming in JavaScript as it allows for a more organized and efficient code structure.
  • Advantage of Class extends in JavaScript

Utilizing the class extends feature in JavaScript offers several advantages, including:

Code reusability

In JavaScript, by utilizing inheritance, it becomes possible for a child class to leverage the methods and properties defined in the parent class, which aids in minimizing redundancy.

Hierarchy Creation

In JavaScript, utilizing the extend keywords allows us to create a hierarchical relationship among classes, thereby enhancing the organization and structure of the code.

Single inheritance

In JavaScript, the language facilitates single inheritance, indicating that a child class can derive from a single parent class exclusively. This approach maintains a clear and organized hierarchy.

Method overriding

In JavaScript, a subclass has the capability to override methods that it inherits from its parent class, providing the opportunity for more tailored behavior.

Polymorphism

In JavaScript, inheritance facilitates polymorphism, enabling a subclass to be utilized in lieu of its superclass, thereby enhancing the adaptability of the code.

Disadvantages of class extends in JavaScript

JavaScript class inheritance, while beneficial, does come with certain drawbacks, including:

Complexity

In JavaScript, the use of inheritance can occasionally add to the intricacy of the code, resulting in challenges related to comprehension and upkeep, particularly within extensive projects.

Tight coupling

In JavaScript, the concept of inheritance establishes a strong connection between parent and child classes. This relationship implies that modifications made to the parent class may influence the child class, potentially resulting in unforeseen problems.

Inflexibility

In JavaScript, once a class structure is created, altering it can prove to be challenging, resulting in code that is less flexible and less responsive to evolving requirements.

Overuse of inheritance

Excessive use of inheritance can occasionally result in an intricate hierarchy that becomes challenging to oversee and comprehend.

Inheritance Hierarchy

The single inheritance approach in JavaScript can result in an extensive inheritance chain, making it challenging to monitor the progression of methods and attributes.

Conflicts

In JavaScript, when two classes within the same inheritance hierarchy contain methods that share identical names, it may result in conflicts and unpredictable behavior.

Memory Usage

Inheritance may result in higher memory consumption since every instance of a child class inherits the attributes and methods of its parent class, regardless of whether they are utilized.

Conclusion

In summary, when implementing inheritance in ES6, it is essential to utilize the extends keyword. The base class, often referred to as the parent class, is the class that is being extended, whereas the subclass, commonly known as the child class, extends this parent or base class.

To invoke the constructor of the parent class, utilize the arguments method within the constructor of the child class. When calling methods from the parent class inside a method of the child class, you can directly employ the super keyword.

Input Required

This code uses input(). Please provide values below: