Prototypes are a fundamental concept in JavaScript that allow objects to inherit 
properties and methods from other objects. 
Every JavaScript object has a prototype, which is another object that it inherits 
properties and methods from.
When a property or method is accessed on an object, JavaScript first looks for 
that property or method on the object itself. 
If its not found, JavaScript then looks for it on the objects prototype. 
If the property or method is not found on the prototype, JavaScript continues 
up the prototype chain until it reaches the top level 
Object.prototype object.
function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.name = function (){
    return this.firstName
  }
}
Person.prototype.name = function() {
  return this.firstName + " " + this.lastName;
};
var p = new Person("sangram","desai",42,"black")
console.log(p.name())
Output:
sangram
If we comment out name function inside Person method then it will call prototypes 
name metho and output will be 
sangram desai
When we call any method on object it first look into that object if not found then 
look into its  prototype.
 
No comments:
Post a Comment