What is actually Prototypes in JavaScript?

0

In JavaScript, a prototype is an object that is associated with every function and object by default. It is a special type of object that can be used to store properties and methods that are shared by all instances of a particular function or object. Prototypes are used to implement inheritance in JavaScript. When you create a new object, it inherits all of the properties and methods from its prototype. This allows you to create reusable code and easily create new objects that are specialized versions of existing objects.

For example, the following code creates a function called Person and defines a property called name on its prototype.

function Person() {
  this.name = "John Doe";
}

Person.prototype.name = "John Doe";

When you create a new object from the Person function, it will inherit the name property from the prototype.

const person = new Person();
console.log(person.name); // "John Doe"

Prototypes can also be used to store methods. For example, the following code defines a method called sayHi() on the prototype of the Person function.

Person.prototype.sayHi = function() {
  console.log("Hi!");
};

When you create a new object from the Person function, it will be able to call the sayHi() method.

const person = new Person();
person.sayHi(); // "Hi!"

Post a Comment

0Comments
Post a Comment (0)