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);
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);
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);
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());
Javascript Prototype – Interview Questions
Q 1: What is a prototype in JavaScript?
Ans: A mechanism to share properties and methods among objects.
Q 2: What is the prototype chain?
Ans: A chain used to look up properties.
Q 3: Which property links the prototype?
Ans: __proto__.
Q 4: Are prototypes objects?
Ans: Yes.
Q 5: Why use prototypes?
Ans: To save memory and enable inheritance.
Javascript Prototype – Objective Questions (MCQs)
Q1. JavaScript uses ______ inheritance.
Q2. Which property links an object to its prototype?
Q3. Where are shared methods stored?
Q4. Prototype methods are shared among ______.
Q5. Which keyword is used to create objects using prototypes?