Prototype
Prototypes are the mechanism by which JavaScript objects inherit features from one another.
In class based languages we have a class which contains all the properties and methods defined inside the class.
When the object of the class is created the newly created object has the access to the properties and the public methods defined inside the class.
Prototype is very similar to the class which acts as the blueprint of the JavaScript objects.
The newly created JavaScript object has access to all the properties and methods of the prototype from which the object is created in addition to its own properties and methods.
Also due to the dynamic nature of the JavaScript we can not only add properties to an object dynamically but we can also add properties to the prototype object which would mean adding a property or behavior to the base class at runtime so that all the newly created objects have access to the properties added dynamically to the prototype object.
// creating an object constructor
function Employee(name, age) {
this.name = name;
this.age = age;
}
//creating an object of type Employee
let Employee1 = new Employee("John", 32);
let Employee2 = new Employee("Mary", 32);
console.log(Employee1);
console.log(Employee2);
//adding property to Employee1 instance dynamically
// it will be available only for this Employee1
Employee1.sports = "Cricket";
//adding property to the prototype of the Employee
//this would add the gender property to all the
//existing object instance of the Employee object
//and would initialize it to null
Employee.prototype.gender = null;
// although Employee3 is created with name and age
// initialized but the gender property would also
//be attached to it and assigned as null because
//of the above mentioned line of code.
let Employee3 = new Employee("Anna", 26);
console.log(Employee1, Employee2, Employee3);
Prototype Chaining
Prototypes are the means of inheritance in JavaScript. The prototype of an object would also have a prototype object. This continues until we reach the top level when there is no prototype object.
This is called prototype chaining or prototype chain in JavaScript.
The properties defined on the prototype objects are also accessible to the object instance. And this is the reason why we are able to access properties which we have not defined explicitly on an object since those are accessible by inheritance through the prototype chaining.
When we try to access any property of an object it is first checked in the own property of the object.
If the property does not exist in the own property then the prototype object is scanned for that property. This continues until we get the property we are accessing or we reach at to the end of prototype chain giving undefined.
console.log(Employee1.__proto__);
console.log(Employee1.__proto__.__proto__);
console.log(Employee1.__proto__.__proto__.__proto__);
Top comments (0)