Introduction
In this blog, I will be explaining function prototype and instance __proto__ properties and how it is defined by JS.
Function prototype
A function's prototype is the object instance that will become the prototype for all objects created using this function as constructor.
Object prototype
An object's prototype is the object instance from which the object is inherited.
Let's refer the below training function example to understand how prototype property is defined for JS function.
Every function is JS have prototype property and objects of those functions have __proto__ property which points to the respective functions.
- function Training(name, version) {
- this.name = name
- this.version = version
- }
- let csharp3 = new Training("c#", "3.0")
- console.log(csharp3.__proto__) // points to Training function
- console.log(Training.prototype) // points to Training function
You can modify only object prototype without impacting function level. changing one object prototype does not impact other function objects.
- csharp3.__proto__.hour = "10"
- console.log(csharp3.__proto__)
- let csharp6 = new Training("c#", "6.0")
- console.log(csharp6.__proto__)
Modifying function level prototype which will be applied to all objects. JS object first checks the property at object level if not present then it requests for __proto__ to get the property.
- Training.prototype.price = "$50"
-
- console.log(csharp6.price) // display $50
- console.log(csharp3.price) // display $50
Overriding function prototype,
- csharp6.price = "$100"
- console.log(csharp6.price)
Inheritence at function level,
- function AdvanceTraning(name, version, price) {
- Training.call(this, name, version)
- this.price = price
- }
- AdvanceTraning.prototype.RevisedPrice = function() {
- return "$120"
- }
- let netcore3 = new AdvanceTraning(".net core", "3.0", "$60")
- console.log(netcore3.RevisedPrice); // you can access all base function proerties like name version etc.
Each function and object have __proto__ property and using that you can identify the parent. the base of all object __proto__ will be object,
- console.log(netcore3.__proto__)
- console.log(netcore3.__proto__.__proto__)
- console.log(netcore3.__proto__.__proto__.__proto__)
Creating prototype with classes,
- class Training
- {
- constructor(name, version)
- {
- this.name = name
- this.version = version
- }
- }
- class AdvanceTraning extends Training
- {
- constructor(name, version, price)
- {
- super(name, version)
- this.price = price
- }
- }
- let netcore3 = new AdvanceTraning(".net core", "3.0", "$50")
- console.log(netcore3.__proto__) // pointing to training class.
Conclusion
In this blog, we studied, JavaScript Prototypes and Inheritance