constructor function: A constructor function will help you to create objects
function display(){
console.log(this);
}
display() // it will refering to the global window object === this
new display() // it will refer to an empty object. basically, whenever we call any function along with the new keyword, it will create an empty object and return the "this"
function productInfo(name, color, price, discount) {
this.name = name;
this.color = color;
this.price = price;
this.discount = discount;
this.displayProductInfo = function () {
console.log(`Product Name is ${this.name} color is ${this.color} price is ${this.price} and discount is ${this.discount} %`);
};
this.getDiscount = () => {
console.log(`total discountis ${this.discount}%`);
};
}
const mi = new productInfo("MI", "Black", "19k", 10);
const vivo = new productInfo("VIVO", "GRAY", "19.6k", 20);
mi.displayProductInfo();
Note: You can access the parameters directly, but if you want to access the normal properties, you must access them through the "THIS" keyword
The disadvantage of a constructor function, if we declare a method, it will allocate memory for every constructor function. Suppose we have 500 objects at that time, it will allocate memory for all the constructor functions.
To overcome this problem through classes or proto object
syntax: objectName.proto.method=function
real-time example: mould
Factory function :
Problem: code duplication