JavaScript Classes & Inheritance Explained! πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

JavaScript Classes and Objects

Introduction to Classes in JavaScript

Classes in JavaScript are a syntactic sugar over prototypes and constructor functions. They provide a cleaner and more readable way to create objects and implement inheritance, but under the hood, they use the same prototype-based structure.

Defining a Class

class User {
    total = 55; // Class field
    constructor(username, email) {
        this.username = username;
        this.email = email;
    }
    print() {
        console.log(this);
    }
}
 
const u1 = new User("death", "dc@dc.com");
u1.print();

Explanation:

  • total: A public class field shared by all instances.
  • constructor: Initializes instance-specific properties.
  • print: A method shared via the prototype.

Inheritance Using Classes

class Programmer extends User {
    constructor(username, email, lang) {
        super(username, email); // Call the parent class constructor
        this.lang = lang;
    }
    print() {
        console.log("PROGRAMMER");
        super.print(); // Call the parent class method
    }
    hello() {
        console.log("Programmer Hello");
    }
}
 
const p1 = new Programmer("death", "dc@dc.com", "JS");
p1.print();

Explanation:

  • extends: Establishes inheritance from the User class.
  • super: Calls the parent class's constructor or methods.
  • Overridden print: Demonstrates polymorphism by modifying behavior.

Deep Inheritance

class Dev extends Programmer {
    constructor(username, email, lang) {
        super(username, email, lang);
    }
}
 
const dev1 = new Dev("code", "code@dc.com", "Python");
console.log(dev1);

Explanation: The Dev class inherits from Programmer, which in turn inherits from User. This demonstrates multi-level inheritance.

Behind the Scenes: Prototypes

Classes in JavaScript are built on prototypes. When you define a class method, it is added to the prototype of the class, and all instances share the same method.

Object.prototype.hello = () => {
    console.log("hello");
};
 
p1.hello(); // hello

Explanation: Extending the Object prototype makes the method available to all objects, but this is generally discouraged as it can lead to conflicts.

Key Features of Classes

  • Syntactic sugar over prototypes and constructor functions.
  • Supports inheritance using extends and super.
  • Encapsulation with class fields and methods.
  • Polymorphism through method overriding.

Best Practices

  • Use classes for better readability and maintainability.
  • Avoid modifying built-in prototypes like Object.prototype.
  • Leverage super for clean inheritance.
Β© 2024 DeathCode. All Rights Reserved.