Sobes.tech
Junior — Middle

Can you explain how prototype inheritance is implemented in JavaScript?

sobes.tech AI

Answer from AI

Prototype inheritance in JavaScript is based on the fact that objects can inherit properties and methods from other objects through a prototype chain.

Each object has a hidden property [[Prototype]] (accessible via proto or Object.getPrototypeOf), which points to another object — the prototype. If a property is not found in the object itself, the search continues in the prototype, then in the prototype's prototype, and so on, until it is found or the chain ends.

Example:

const animal = {
  eats: true
};

const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.eats); // true — inherited from animal
console.log(rabbit.jumps); // true — own property

Here, rabbit inherits from animal through the prototype.

Constructor functions also use the prototype property to set the prototype of created objects:

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  console.log('Hello, ' + this.name);
};

const alice = new Person('Alice');
alice.greet(); // Hello, Alice

Thus, prototype inheritance is a dynamic chain of objects that allows reusing properties and methods without classes.

Can you explain how prototype inheritance is… - sobes.tech