Prototypes in JavaScript

·

1 min read

In JavaScript, a prototype is an object that serves as a template or blueprint for other objects to inherit properties and methods from. Every object in JavaScript has a prototype, except for the root object, Object.prototype.

When an object is created in JavaScript, it is linked to its prototype through an internal property called __proto__ (or [[Prototype]]). This linkage allows the object to access properties and methods defined in its prototype.

A prototype object can be created in JavaScript using either the object literal notation or the Object.create() method. For example:

// Object literal notation
const myPrototype = {
  method1() {
    console.log('Hello from method 1');
  },
  method2() {
    console.log('Hello from method 2');
  }
};

// Object created with the prototype
const myObject = Object.create(myPrototype);

In the above example, myObject is created with myPrototype as its prototype. It can access method1 and method2 defined in the prototype through the __proto__ property.

Prototypes are used extensively in JavaScript to implement inheritance, where objects can inherit properties and methods from their prototype, which in turn can inherit from their own prototype. This forms a prototype chain, which allows objects to share common functionality and reduces duplication of code.