Prototype is used to define classes or objects in JavaScript. Classes or objects are building blocks of Object Oriented Programming.
Introduction
The prototype object of javascript introduced in Javascript 1.1. In Visual Studio, you can get intellisense or its properties and methods.
Use of prototype
Prototype prebuilt simplifies the process of adding custom properties/methods to all instances of an object. Keep the below code snippet in the html or aspx page and run it, you will notice that you will get a alert message.
Example:
<script language="javascript">
// create the prototype
function Car(cName, cModel) {
this.carName = cName;
this.carModel = cModel;
}
// declare another property
Car.prototype.price = 200000;
// now create a GetCarDetails function that will show the details
Car.prototype.GetCarDetails = function () {
return "Car Name:" + this.carName + " Car Model:" + this.carModel + " Car Price: " + this.price;
}
// now create the object of Car prototype
var oCar = new Car("Maruti Alto", "2009");
// Call the function that we created
alert(oCar.GetCarDetails() + oCar.Engine);
/******************
Car.prototype={
Price: 200000,
GetCarDetails = function ()
{
return "Car Name:"+this.carName+" Car Model:"+this.carModel+" Car Price: "+this.price;
}
}
******************/
</script>
Conclusion
Prototype offers better performance in some browser(Firefox), and they provide better support for reflection, Intellisense and debugging.