What is prototype in Javascript? Explain prototype with a basic example

What is prototype?

A prototype in Javascript is an object from which all other objects inherit properties and methods.

Basic Javascript prototype example

function Cars(carBrandName){
  this.name = carBrandName;
};

Cars.prototype.getCarBrandName = function(){
  return (this.name) ? this.name : 'BMW'
};

var carObj1 = new Cars("Audi");
console.log(carObj1.getCarBrandName());

var carObj2 = new Cars("Tesla");
console.log(carObj2.getCarBrandName());

Prototype example explanation

In the above example the function Cars simply sets the car brand name and to show that car brand we have defined a method called getCarBrandName in the prototype property of Cars function. As we have defined the method in the prototype property, it will be shared among all the instance of the function Cars.

Comments