JavaScript Inheritance

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:00:30

Class Inheritance:

Class inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or derived class) to inherit properties and methods from an existing class (base class or superclass). It promotes code reusability and hierarchy in code structure.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}
class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}
const myDog = new Dog("Buddy");
myDog.speak(); // Output: Buddy barks.  

Getters and Setters:

Getters and setters are special methods in a class that allow controlled access to an object's properties. Getters retrieve the value of a property, while setters set or modify it, often providing validation or encapsulation for the property.

Example:

class Circle {
  constructor(radius) {
    this._radius = radius; // Conventionally, use an underscore to denote private property
  }
  get radius() {
    return this._radius;
  }
  set radius(newRadius) {
    if (newRadius >= 0) {
      this._radius = newRadius;
    } else {
      console.log("Radius cannot be negative.");
    }
  }
  area() {
    return Math.PI * this._radius ** 2;
  }
}
const myCircle = new Circle(5);
console.log(myCircle.radius); // Getter: 5
myCircle.radius = 10; // Setter
console.log(myCircle.radius); // Getter: 10
myCircle.radius = -2; // Setter: Radius cannot be negative.  

Hoisting:

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, allowing you to use them before they are declared in your code.

Example:

console.log(x); // Output: undefined (Variable declaration is hoisted)
var x = 5;
sayHello(); // Output: "Hello, World!" (Function declaration is hoisted)
function sayHello() {
  console.log("Hello, World!");
}
// Function expressions are not hoisted
greet(); // Error: greet is not a function
var greet = function () {
  console.log("Hi!");
};  
Self-paced Membership
  • 24+ Video Courses
  • 850+ Hands-On Labs
  • 500+ Quick Notes
  • 225+ Skill Tests
  • 120+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this