what is prototype in js

3 hours ago 5
Nature

In JavaScript, a prototype is an object from which other objects inherit properties and methods. It is the core mechanism behind JavaScript's inheritance system, allowing objects to share functionality without duplicating code.

Key Points About Prototype in JavaScript

  • Every JavaScript object has an internal link to another object called its prototype. This prototype object can have its own prototype, forming a prototype chain that ends when an object’s prototype is null
  • When you try to access a property or method on an object, JavaScript first looks for it on the object itself. If it is not found, it searches the object's prototype, then the prototype's prototype, and so on up the chain until the property is found or the chain ends
  • The property that points to an object's prototype is not named prototype; instead, it is accessed via Object.getPrototypeOf(obj) or the non-standard __proto__ property in many browsers
  • The top of the prototype chain is Object.prototype, which provides basic methods like toString() that are available on almost all objects
  • You can set or change an object's prototype using methods like Object.create() (to create a new object with a specified prototype) or Object.setPrototypeOf() (to change an existing object's prototype)
  • Constructor functions have a special property called prototype. When you create an instance using new, the instance’s internal prototype is set to the constructor function’s prototype object, enabling shared methods among all instances

Example

js

const personPrototype = {
  greet() {
    console.log("hello!");
  }
};

const carl = Object.create(personPrototype);
carl.greet(); // Outputs: hello!

Here, carl does not have its own greet method, but it inherits it from personPrototype via the prototype chain

Summary

The prototype in JavaScript is an object that acts as a template or blueprint for other objects, enabling inheritance and shared behavior. It is fundamental to how JavaScript objects work and how properties and methods are looked up and shared among objects. This prototype-based inheritance differs from classical inheritance in other languages but provides a flexible and dynamic way to extend and reuse code