Member-only story
Shadowing properties in the prototype chain is a concept in JavaScript that can lead to unexpected behavior if not understood properly.
In this guide, we’ll explore what shadowing properties are, how they occur, and provide clear examples to help you grasp this important concept effectively.
What is Shadowing?
In JavaScript, shadowing occurs when a property in a child object hides or overrides a property with the same name in its prototype chain. This can lead to confusion and unexpected behavior if not managed correctly.
Understanding Shadowing with Examples
Let’s start by understanding shadowing with a simple example:
const parent = {
greet: function() {
console.log('Hello from parent');
}
};
const child = Object.create(parent);
child.greet = function() {
console.log('Hello from child');
};
child.greet(); // Output: Hello from child
In this example, the child
object shadows the greet
method defined in its prototype (parent
)…