Let me explain the varied way of making objects in JavaScript. one among the ways to make objects in JavaScript is that the constructor function. Consider the below constructor function:
function Bike(model,color){
this.model = model,
this.color = color,this.getDetails = function(){
return this.model+' bike is '+this.color;
}
}
var bikeObj1 = new Bike('BMW','BLACK');
var bikeObj2 = new Bike('BMW','WHITE');console.log(bikeObj1.getDetails()); //output: BMW bike is BLACK
console.log(bikeObj2.getDetails()); //output: BMW bike is WHITE
In the above example, we are creating two objects, bikeObj1, bikeObj2 employing a constructor. In JavaScript, every object has its own methods and properties. In our example, two objects have two instances of the constructor function getDetails(). It doesn’t add up having a replica of getDetails doing an equivalent thing.
Instead ofemploying a copy of instances, we are getting to use the prototype property of a constructor function.
Instead of
Prototype
When an object is made in JavaScript, JavaScript engine adds a __proto__ property to the newly created object which is named dunder proto. dunder proto or __proto__ points to the prototype object of the constructor function.
function Bike(model,color){
this.model = model,
this.color = color
}Bike.prototype.getDetails = function(){
return this.model+" bike is "+this.color;
}
var bikeObj1 = new Bike(‘BMW’,’Black’);console.log(bikeObj1.getDetails());
The bikeObj1 object, which is made using the Bike constructor function, features a dunder proto or __proto__ property which points to the prototype object of the constructor function Bike.
In below code, both bikeObj1 it's dunder proto or __proto__ property and Bike.prototype property is equal. Let’s check if they point at an equivalent location using === operator.
console.log(bikeObj1.__proto__ === Bike.prototype );//output : true
TK [Not sure what the author intends to mention here] So using prototype property, what percentage objects are created functions are loaded into memory just one occasion and that we can override functions if required. JavaScript Prototype
0 Comments