0
0
Javascriptprogramming~5 mins

Prototype chain in Javascript

Choose your learning style9 modes available
Introduction

The prototype chain helps JavaScript objects share features like properties and functions. It works like a family tree where objects can borrow things from their parents.

When you want many objects to share the same behavior without copying code.
When you want to find a property or method that an object does not have directly.
When you want to create new objects based on existing ones and add or change features.
When debugging to understand where a property or method is coming from.
When using built-in objects like arrays or strings and want to know how their methods work.
Syntax
Javascript
object.__proto__
// or
Object.getPrototypeOf(object)

__proto__ is a way to access an object's prototype, but it's better to use Object.getPrototypeOf() for clarity.

The prototype chain ends when an object has null as its prototype.

Examples
The child object does not have greet itself, so JavaScript looks up the prototype chain to parent and finds it.
Javascript
const parent = { greet() { return 'Hello'; } };
const child = Object.create(parent);
console.log(child.greet());
Arrays inherit methods like toString from Array.prototype through the prototype chain.
Javascript
const arr = [];
console.log(arr.toString());
This shows that parent is the prototype of child.
Javascript
console.log(Object.getPrototypeOf(child) === parent);
Sample Program

Here, dog does not have its own speak method, so it uses the one from animal via the prototype chain.

Javascript
const animal = {
  speak() {
    return `${this.name} makes a sound.`;
  }
};

const dog = Object.create(animal);
dog.name = 'Buddy';
console.log(dog.speak());
OutputSuccess
Important Notes

Every object in JavaScript has a prototype except the base object which has null as its prototype.

Changing the prototype of an object after creation is possible but can slow down your code, so it's best to set it when creating the object.

Use Object.create() to create a new object with a specific prototype easily.

Summary

The prototype chain lets objects share properties and methods.

JavaScript looks up the chain to find missing properties or methods.

Use Object.create() and Object.getPrototypeOf() to work with prototypes clearly.