Javascript Prototype

prototype is a most important part of the JavaScript. If you create the object then property and method of this object always inherit from the prototype.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1);

Output:-


Student {firstName: "John", lastName: "Mathew", age: 35}
age: 35
firstName: "John"
lastName: "Mathew"
__proto__:
constructor: ƒ Student(first_name, last_name, age)
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

Why the need of the prototype in the property and methods?

Prototype is used to add property or method after created the constructor function.

Suppose you have Student constructor function which have 3 parameters first_name, last_name and age.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

Add Property after created the constructor function

Now, you want to add new property class after created the constructor function.

Student.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- undefined

Now, you will use prototype to add into property after created the constructor function.

Example:-


Student.prototype.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- MCA

Add method after created the constructor function


Student.address= function(){
	
 return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address);
Uncaught TypeError: stu1.address is not a function

Now, you will add prototype in the method after created the constructor function


Student.prototype.address= function(){
	
	return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address());
Output:- Laxmi Nagar, New Delhi