What is the Prototype in JavaScript?

09/30/2021

Contents

In this article, you will learn about the prototype in JavaScript.

The Prototype in JavaScript

In JavaScript, the prototype is an object that serves as a blueprint for creating other objects. Every object in JavaScript has a prototype, and this prototype can be used to define shared properties and methods that are available to all instances of the object.

The prototype is a fundamental concept in JavaScript’s object-oriented programming paradigm, and it allows for the creation of efficient and reusable code. When an object is created, it is linked to its prototype object, and any properties or methods that are not defined directly on the object itself are inherited from the prototype.

In JavaScript, there are two ways to define a prototype. The first is to use the prototype property of a constructor function. Constructor functions are special functions that are used to create new objects, and the prototype property of a constructor function is used to define properties and methods that are shared by all instances of the object.

For example, let’s say we have a constructor function called Person that creates new instances of a person object:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

We can define a shared method for all instances of Person by adding it to the Person.prototype object:

Person.prototype.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

Now, every instance of Person that is created will have access to the sayHello method:

const john = new Person("John", 30);
john.sayHello(); // logs "Hello, my name is John"

The second way to define a prototype is to use the Object.create method. This method creates a new object and links it to a specified prototype object. For example:

const personPrototype = {
  sayHello: function() {
    console.log("Hello, my name is " + this.name);
  }
};

const john = Object.create(personPrototype);
john.name = "John";
john.sayHello(); // logs "Hello, my name is John"

In this example, we first define a prototype object called personPrototype that contains a sayHello method. We then create a new object called john and link it to personPrototype using Object.create. Finally, we set the name property on john and call the sayHello method.