Module 6: Modern JavaScript, OOP, and Data
Prototypes and the Prototype Chain
Understand property lookup and JavaScript object delegation.
JavaScript objects can delegate property lookup to another object called their prototype. If a property is not found on the object itself, JavaScript checks its prototype, then that prototype's prototype, continuing until the chain ends.
const animal = {
speak() {
return "A sound";
},
};
const dog = Object.create(animal);
dog.bark = () => "Woof";
console.log(dog.bark()); // "Woof"
console.log(dog.speak()); // inherited from animal
Object.create explicitly chooses the prototype for a new object. Most object literals inherit from Object.prototype, which contains common methods. A null-prototype object can be useful for certain dictionaries, but choose it deliberately.
Own versus inherited properties#
Object.hasOwn(dog, "bark") is true, while Object.hasOwn(dog, "speak") is false. The in operator checks both own and inherited properties.
Prototype pollution awareness#
Do not blindly merge untrusted objects into sensitive configuration objects. Be careful with dynamic property keys and object merging, and prefer well-defined schemas and safe data handling. This matters when processing external JSON.
Classes#
JavaScript class syntax is built on prototypes. Classes make constructor and method definitions more familiar, but method lookup still follows prototype mechanics. The next lesson explores classes and inheritance.
Practice#
Create an object with a prototype method, create another object that delegates to it, and test which properties are own versus inherited.