Understanding JavaScript Inheritance and Prototype

🚀 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲, __𝗽𝗿𝗼𝘁𝗼__, 𝗮𝗻𝗱 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Most JavaScript developers use objects daily… But not everyone truly understands how JavaScript inheritance actually works under the hood. Let’s break it down simply 👇 🔹 𝟭️ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲? In JavaScript, every function automatically gets a special property called: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗡𝗮𝗺𝗲.𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 It is used when we create objects using new. Example: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗣𝗲𝗿𝘀𝗼𝗻(𝗻𝗮𝗺𝗲) {  𝘁𝗵𝗶𝘀.𝗻𝗮𝗺𝗲 = 𝗻𝗮𝗺𝗲; } 𝗣𝗲𝗿𝘀𝗼𝗻.𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲.𝘀𝗮𝘆𝗛𝗲𝗹𝗹𝗼 = 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 () {  𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴("𝗛𝗲𝗹𝗹𝗼 " + 𝘁𝗵𝗶𝘀.𝗻𝗮𝗺𝗲); }; 𝗰𝗼𝗻𝘀𝘁 𝘂𝘀𝗲𝗿 = 𝗻𝗲𝘄 𝗣𝗲𝗿𝘀𝗼𝗻("𝗔𝗺𝗮𝗻"); 𝘂𝘀𝗲𝗿.𝘀𝗮𝘆𝗛𝗲𝗹𝗹𝗼(); // 𝗛𝗲𝗹𝗹𝗼 𝗔𝗺𝗮𝗻 Here: sayHello is not copied into every object It is shared via the prototype This saves memory 🔹 𝟮️ 𝗪𝗵𝗮𝘁 𝗶𝘀 __𝗽𝗿𝗼𝘁𝗼__? __proto__ is a reference to an object's parent prototype. console.log(user.__proto__ === Person.prototype);  // true Important: prototype → belongs to functions __proto__ → belongs to objects Think of it like this: function → prototype object → __proto__ 🔹 𝟯️ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 𝗖𝗵𝗮𝗶𝗻𝗶𝗻𝗴? When you try to access a property: user.sayHello() JavaScript searches like this: Does user have sayHello? ❌ Check user.__proto__ (Person.prototype) ✅ If not found, go to next prototype Eventually reaches Object.prototype This chain is called: 👉 Prototype Chaining 🔹 𝟰️.𝗪𝗵𝘆 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗣𝗼𝘄𝗲𝗿𝗳𝘂𝗹? Because JavaScript inheritance is: Dynamic Memory efficient Flexible Every object in JavaScript is connected to a prototype. Even this works: [].__proto__ === Array.prototype Everything eventually links to: Object.prototype 🔥 Final Takeaway prototype → used by constructor functions __proto__ → internal link to parent Prototype chaining → how JavaScript finds properties Arrow functions ❌ don’t have prototype 𝗜𝗳 𝘆𝗼𝘂'𝗿𝗲 𝗹𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗱𝗲𝗲𝗽𝗹𝘆, 𝗱𝗼𝗻’𝘁 𝘀𝗸𝗶𝗽 𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀. 𝗧𝗵𝗲𝘆 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗼𝗳 𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝗲𝗮𝗹𝗹𝘆 𝘄𝗼𝗿𝗸𝘀. 💡 #JavaScript #WebDevelopment #Programming #CodingTips #CareerGrowth #DevCommunity

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories