𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀

ఒకే విధమైన నిర్మాణాన్ని (structure) కలిగి ఉన్న అనేక ఆబ్జెక్ట్‌లను సృష్టించడానికి constructor functions ఉపయోగించండి.

ఒక constructor function బ్లూప్రింట్‌లా పనిచేస్తుంది. ఈ బ్లూప్రింట్ నుండి ఆబ్జెక్ట్‌లను నిర్మించడానికి మీరు new కీవర్డ్‌ను ఉపయోగిస్తారు. constructor పేర్లను ఎల్లప్పుడూ క్యాపిటల్ లెటర్‌తో ప్రారంభించాలి.

ఇది ఎలా పనిచేస్తుంది:

మీరు new కీవర్డ్‌ను ఉపయోగించినప్పుడు, JavaScript నాలుగు పనులు చేస్తుంది:

this కీవర్డ్ చాలా ముఖ్యం. ఫంక్షన్ లోపల, this అనేది మీ కొత్త ఆబ్జెక్ట్‌ను సూచిస్తుంది.

ఉదాహరణ:

function Employee(name, salary) { this.name = name; this.salary = salary; }

const emp1 = new Employee("Ram", 50000); const emp2 = new Employee("Kumar", 60000);

రెండు ఆబ్జెక్ట్‌లు ఒకే నిర్మాణాన్ని కలిగి ఉంటాయి.

మెథడ్స్‌ను జోడించడం (Adding methods):

మీరు constructor లోపల ఫంక్షన్‌లను జోడించవచ్చు.

function Employee(name, salary) { this.name = name; this.salary = salary; this.displayInfo = function() { console.log(this.name + " earns " + this.salary); }; }

మెమరీ మేనేజ్‌మెంట్ (Memory management):

Constructor లోపల నేరుగా మెథడ్స్‌ను జోడించడం వల్ల ప్రతి ఆబ్జెక్ట్‌కు ఒక కొత్త కాపీ సృష్టించబడుతుంది. దీనివల్ల ఎక్కువ మెమరీ వినియోగించబడుతుంది.

దానికి బదులుగా, prototype ప్రాపర్టీని ఉపయోగించండి.

Employee.prototype.greet = function() { console.log("Hello " + this.name); };

ఇప్పుడు, ప్రతి ఉద్యోగి ఒకే ఒక greet మెథడ్ కాపీని పంచుకుంటారు. ఇది మీ కోడ్‌ను మరింత సమర్థవంతంగా (efficient) చేస్తుంది.

సారాంశం (Summary):

Source: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k