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

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

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

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

ఉదాహరణ కోడ్:

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

const emp1 = new Employee("Saravanan", 50000);

పాటించవలసిన నియమాలు:

this యొక్క పాత్ర:

ఒక constructor లోపల, this అనేది మీరు సృష్టిస్తున్న నిర్దిష్ట ఆబ్జెక్ట్‌ను సూచిస్తుంది. ఉదాహరణకు, this.name = name అనేది పారామీటర్ విలువను ఆబ్జెక్ట్ ప్రాపర్టీకి కేటాయిస్తుంది.

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

ప్రతి ఆబ్జెక్ట్ కూడా ఉపయోగించుకునేలా మీరు constructor లోపల ఫంక్షన్‌లను జోడించవచ్చు.

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

మెమరీ సామర్థ్యం (Memory efficiency):

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

దానికి బదులుగా, prototypeని ఉపయోగించండి. Prototype కి ఒక మెథడ్‌ను జోడించడం వల్ల, ఆ మెథడ్ యొక్క ఒకే ఒక కాపీని అన్ని ఆబ్జెక్ట్‌లు పంచుకుంటాయి.

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

సారాంశం:

మూలం: https://www.w3schools.com/js/js_object_constructors.asp మూలం: https://www.geeksforgeeks.org/javascript/javascript-function-constructor/ మూలం: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

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