Prototype in JavaScript

·

2 min read

In JavaScript, a prototype is an object from which other objects can inherit properties. It's part of JavaScript's implementation of a key concept in Object Oriented Programming: inheritance.

JavaScript is a bit unique in that it is a prototype-based language, rather than a class-based language (although classes were introduced in ES6, they are mostly syntactic sugar over prototypes). In class-based languages, classes define the properties and methods of an object, and then instances of the class are created with the new keyword. However, in JavaScript, any object can be a prototype for another object, allowing the new object to inherit properties and methods from the prototype.

Here's an example of how prototypes work in JavaScript:

let animal = {
  type: 'Animal',
  describe() {
    return `Type: ${this.type}`;
  }
};

let dog = Object.create(animal);
dog.type = 'Dog';

console.log(dog.describe());  // Outputs: 'Type: Dog'

In this example, animal is a prototype with a property type and a method describe(). Then dog is created as a new object with animal as its prototype, and dog's type property is changed. When describe() is called on dog, the method is not found on dog itself, so JavaScript looks up the prototype chain and finds it on animal, then calls the method with this bound to dog.

Each JavaScript object has a private property [[Prototype]] which is a link to the object's prototype. This link is used in the prototype chain lookup process.

Note that JavaScript's Function objects also have a prototype property (different from [[Prototype]]), which is used when new objects are created with that function as a constructor. The new object's [[Prototype]] will be set to the constructor function's prototype object.

In general, JavaScript's prototype system provides a flexible mechanism for object-to-object inheritance, as opposed to the more rigid class-to-instance inheritance found in many other languages.

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/