JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Object Prototypes

14 April 2025 | Category:

In JavaScript, every object has a prototype. A prototype is another object that your object inherits properties and methods from.

Think of prototypes as a blueprint or parent object from which other objects can get shared behavior.


🔁 What Is a Prototype?

When you create a JavaScript object, it automatically gets linked to a prototype object. This allows property and method sharing between objects.

Example:

const person = {
  greet: function() {
    console.log("Hello!");
  }
};

const user = Object.create(person);

user.greet(); // Output: Hello!

Here:

  • user doesn’t have its own greet() method.
  • JavaScript looks up the prototype chain and finds greet() in person.

🧠 Understanding the Prototype Chain

When you try to access a property or method on an object:

  1. JavaScript first checks if it’s in the object itself.
  2. If not found, it looks at the object’s prototype.
  3. It keeps going up the chain until it finds the property or reaches null.
user → person → Object.prototype → null

🛠️ Using __proto__ (not recommended in production)

const obj = {};
console.log(obj.__proto__); // Shows Object.prototype

__proto__ is a getter/setter for an object’s internal prototype. Use it only for learning or debugging.


🧱 Every Function Has a prototype Property

When you create a function, it automatically gets a .prototype object:

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

Animal.prototype.speak = function() {
  console.log(`${this.name} makes a sound.`);
};

const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a sound.
  • speak() is defined on Animal.prototype
  • All objects created using new Animal() share this method

🔍 Difference: prototype vs __proto__

TermMeaning
prototypeA property of constructor functions used when creating new objects
__proto__The actual internal prototype link of an object (points to another object)

✅ Benefits of Using Prototypes

  • Memory efficient: Methods are shared across instances instead of copied
  • Inheritance: Makes it easier to create parent-child relationships between objects
  • Foundation of JS OOP: Classes in JavaScript are syntactic sugar over prototype-based inheritance

💡 Modern Use: Classes Behind the Scenes

When you use ES6 classes, JavaScript still uses prototypes under the hood:

class User {
  sayHi() {
    console.log("Hi!");
  }
}

const u1 = new User();
u1.sayHi(); // Inherited from User.prototype