In the world of JavaScript, understanding inheritance and the concept of shadowing properties is crucial for writing clean, maintainable code. Shadowing properties can lead to unexpected behavior, and it’s essential to grasp how it works to avoid potential bugs and ensure your code functions as intended.
Let’s start with a simple example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal('Fluffy');
const dog = new Dog('Buddy');
animal.speak(); // Fluffy makes a sound.
dog.speak(); // Buddy barks.
In this example, we have a base class Animal
and a derived class Dog
that inherits from Animal
. Both classes have a speak
method, but they behave differently because of shadowing properties.
When you create an instance of Dog
and call its speak
method, the speak
method defined in the Dog
class is executed, not the one from the Animal
class. This is because the speak
method in the Dog
class "shadows" or overrides the speak
method in the…