Prototypes & the Prototype Chain in JavaScript

Prototypes & the Prototype Chain If you’re using class in JavaScript, you’re already using prototypes whether you realize it or not. Today was about understanding what that actually means under the hood. What I focused on Prototypes & the chain Every object in JavaScript has an internal link to another object called its prototype. You don’t see it directly, but it’s always there. When you try to access a property, JavaScript follows a simple process: * First, it checks the object itself * If not found, it looks at the object’s prototype * If still not found, it keeps going up the chain * This continues until it either finds the property or reaches null That lookup flow is called the prototype chain. A simple example: ``` function Person(name) {  this.name = name; } Person.prototype.sayHello = function () {  return "Hello " + this.name; }; const user = new Person("Naim"); console.log(user.sayHello()); ``` Here’s what’s happening: * `user` does not have `sayHello` directly * JavaScript looks at `Person.prototype` * It finds `sayHello` there and executes it That’s the prototype chain in action. Manual inheritance (no class) Built inheritance from scratch using constructor functions to understand how objects can share behavior. ``` function Animal(name) {  this.name = name; } Animal.prototype.speak = function () {  return this.name + " makes a sound"; }; function Dog(name) {  this.name = name; } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; const d = new Dog("Rex"); console.log(d.speak()); ``` What’s happening here: * `Dog` doesn’t have `speak` * Its prototype is linked to `Animal.prototype` * So JavaScript finds `speak` there through the chain This is the same mechanism behind class-based inheritance. Modifying prototypes A few behaviors stood out while testing: * Adding a method to a prototype affects all existing instances * Property lookup happens at runtime, not when the object is created * If an object defines its own property, it overrides the prototype (shadowing) Example: ``` Person.prototype.age = 25; console.log(user.age); // 25 user.age = 30; console.log(user.age); // 30 (shadows prototype) ``` Takeaway Prototypes are how JavaScript actually shares behavior between objects. The prototype chain is how JavaScript resolves properties. Once this clicks, things like inheritance, method sharing, and even some common bugs start making a lot more sense. #javascript #webdevelopment #frontend #learninginpublic

  • Infographic showing the JavaScript Prototype Chain with code examples for Dog inheritance and property shadowing.

To view or add a comment, sign in

Explore content categories