What are object prototypes in javascript?

In JavaScript, a prototype is an object that is associated with every function and allows you to share properties and methods between multiple instances of that function. Every JavaScript function has a prototype property, which is an object that contains properties and methods that are shared by all instances of that function.

When a new instance of a function is created using the “new” keyword, JavaScript creates a new object and sets its prototype to the prototype property of the function. This means that any properties or methods that are added to the prototype property will be available to all instances of the function.

Prototypes are commonly used in JavaScript to implement inheritance, which allows you to create new objects that inherit properties and methods from existing objects. By setting the prototype of a new object to an existing object, you can create a new object that shares the properties and methods of the existing object.

For example, consider a constructor function for a Person object:

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

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

In this example, we define a constructor function for a Person object that takes a name and age as arguments. We then add a “greet” method to the prototype property of the Person function. This method logs a greeting to the console that includes the person’s name.

Now, if we create two instances of the Person object:

var person1 = new Person("Alice", 30);
var person2 = new Person("Bob", 35);

Both person1 and person2 will have access to the “greet” method, since it is defined on the prototype property of the Person function. This allows us to share code between multiple instances of the Person object, without having to define the same method multiple times.