Prototype Inheritance, Chaining, and Property Shadowing in JavaScript
JavaScript’s prototype-based inheritance system is fundamental to understanding how objects and their properties interact. This article explores prototype inheritance, chaining, and property shadowing, crucial concepts for writing effective and maintainable JavaScript code.
Prototype Inheritance and Chaining
Prototype inheritance allows objects to inherit properties and methods from other objects. Unlike classical inheritance, JavaScript uses prototypes for this purpose. Every object in JavaScript has a prototype, which is itself an object. This prototype can have its own prototype, forming a prototype chain.
When accessing a property or method, JavaScript first checks the object itself. If the property is not found, JavaScript continues the search up the prototype chain. This process continues until it either finds the property or reaches Object.prototype, the root of all objects. This process is known as chaining and is essential for understanding how inheritance works in JavaScript.
Example of Prototype Inheritance Using :
const teacher = {
greet: function() {
console.log("Hello from teacher");
}
};
const student = Object.create(student);
student.name = "Roman";
student.greet(); // Outputs: "Hello from teacher"
领英推荐
In this example, teacher is an object with a greet method. The child object is created with teacher as its prototype using Object.create(). This setup allows student to inherit the greet method from teacher. When student.greet() is called, JavaScript looks up the prototype chain and finds the greet method on teacher, demonstrating how prototype inheritance works.
Property Shadowing
Property shadowing occurs when an object has a property with the same name as one in its prototype. The object’s property shadows or overrides the prototype’s property, making the prototype’s property inaccessible through the object.
Example of Property Shadowing:
let obj = {
name: "hello",
__proto__: {
name: "helloWorld"
}
};
console.log(obj.name); // Outputs: "hello"
In this example, obj has its own name property with the value "hello". Its prototype (__proto__) also has a name property with the value "helloWorld". When obj.name is accessed, JavaScript first looks at obj and finds its own name property. The name property in the prototype is shadowed, and thus not accessed, resulting in the output "hello".