HomeJAVASCRIPTWhat is prototype and prototypal inheritance?

What is prototype and prototypal inheritance?

Prototype

In JavaScript, every object has an internal hidden property called [[Prototype]] (often accessed using __proto__ or through Object.getPrototypeOf()).

  • This prototype is a reference to another object.
  • The prototype object can have its own properties and methods.
  • When you try to access a property or method on an object, JavaScript first looks at the object itself.
    • If it doesn’t find it, it looks at the object’s prototype.
    • If not found there, it goes further up the prototype chain until it reaches null.

👉 Example:

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

let student = Object.create(person); // student’s prototype is person
student.name = "John";

student.greet(); // "Hello!" (inherited from prototype)

Here:

  • student doesn’t have a greet method.
  • JavaScript looks at student.__proto__ (which is person) and finds greet.

Prototypal Inheritance

Prototypal inheritance is the mechanism by which one object can inherit properties and methods from another object via its prototype.

Key points:

  1. Objects can serve as prototypes for other objects.
  2. This allows property/method sharing without duplication.
  3. It forms a chain known as the prototype chain.

👉 Example with constructor functions:

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

Animal.prototype.speak = function() {
  console.log(this.name + " makes a noise.");
};

let dog = new Animal("Dog");
dog.speak(); // "Dog makes a noise."

Here:

  • Animal.prototype has the speak method.
  • dog doesn’t have speak directly, but it inherits it via its prototype.

In short:

  • Prototype = the object that provides a fallback for another object’s properties.
  • Prototypal Inheritance = the process where objects inherit properties/methods from other objects via the prototype chain.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *