SmartCodingTips

πŸ”— JavaScript Prototypes

In JavaScript, every object has a hidden internal property called [[Prototype]] which can be accessed using __proto__ or more reliably through Object.getPrototypeOf(). Prototypes allow objects to share properties and methods.

πŸ“š What is a Prototype?

Think of prototypes as inheritance in JavaScript. When you try to access a property or method on an object, JavaScript will look at the object first. If it doesn't find it, it goes up the prototype chain.

πŸ› οΈ Constructor Function and Prototype

function Person(name) {
  this.name = name;
}

// Adding method to prototype
Person.prototype.greet = function() {
  console.log("Hi, I’m " + this.name);
};

const john = new Person("John");
john.greet(); // "Hi, I’m John"

πŸ” Prototype Chain Example

console.log(john.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true

πŸš€ Using Object.create()

You can also manually create objects with a specific prototype using Object.create().

const animal = {
  speak() {
    console.log("I can speak");
  }
};

const dog = Object.create(animal);
dog.speak(); // "I can speak"

🧠 Summary

  • All JavaScript objects have a prototype.
  • Methods and properties can be added to constructor function’s prototype.
  • Prototype chain enables inheritance.
  • Use Object.create() to set prototypes manually.
πŸ’‘ Tip: Understanding prototypes helps in debugging, memory optimization, and writing reusable object-oriented code.