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.
Prototype chain in 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.
child object does not have greet itself, so JavaScript looks up the prototype chain to parent and finds it.const parent = { greet() { return 'Hello'; } }; const child = Object.create(parent); console.log(child.greet());
toString from Array.prototype through the prototype chain.const arr = []; console.log(arr.toString());
parent is the prototype of child.console.log(Object.getPrototypeOf(child) === parent);
Here, dog does not have its own speak method, so it uses the one from animal via the prototype chain.
const animal = { speak() { return `${this.name} makes a sound.`; } }; const dog = Object.create(animal); dog.name = 'Buddy'; console.log(dog.speak());
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.
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.