𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀
Constructor function એ objects માટે એક બ્લુપ્રિન્ટ છે. સમાન માળખાવાળા ઘણા objects બનાવવા માટે તેનો ઉપયોગ કરો.
તે કેવી રીતે કામ કરે છે:
તમે constructor function ને કોલ કરવા માટે new keyword નો ઉપયોગ કરો છો. આ પ્રક્રિયા ચાર વસ્તુઓ કરે છે:
- તે એક ખાલી object બનાવે છે.
- તે
thisને તે નવા object તરફ નિર્દેશિત કરવા માટે સેટ કરે છે. - તે function ની અંદરના કોડને એક્ઝિક્યુટ કરે છે.
- તે નવો object રિટર્ન કરે છે.
Example code:
function Employee(name, salary) {
this.name = name;
this.salary = salary;
}
const emp1 = new Employee("Saravanan", 50000);
અનુસરવાના નિયમો:
- Function ના નામ કેપિટલ અક્ષરથી શરૂ કરો.
- નવા object ને properties અસાઇન કરવા માટે
thisનો ઉપયોગ કરો.
this ની ભૂમિકા:
Constructor ની અંદર, this એ તમે જે ચોક્કસ object બનાવી રહ્યા છો તેને સંદર્ભિત કરે છે. ઉદાહરણ તરીકે, this.name = name એ parameter ની કિંમતને object property ને અસાઇન કરે છે.
Methods ઉમેરવા:
તમે constructor ની અંદર functions ઉમેરી શકો છો જેથી દરેક object તેનો ઉપયોગ કરી શકે.
function Employee(name, salary) {
this.name = name;
this.salary = salary;
this.displayInfo = function() {
console.log(this.name + " earns " + this.salary);
};
}
મેમરી કાર્યક્ષમતા (Memory efficiency):
જો તમે સીધા constructor માં methods ઉમેરો છો, તો દરેક object ને તેની પોતાની કોપી મળે છે. આનાથી વધુ મેમરી વપરાય છે.
તેના બદલે, prototype નો ઉપયોગ કરો. Prototype માં method ઉમેરવાથી તમામ objects વચ્ચે એક જ કોપી શેર થાય છે.
Employee.prototype.greet = function() {
console.log("Hello " + this.name);
};
સારાંશ:
- સિંગલ object માટે object literals નો ઉપયોગ કરો.
- સમાન માળખાવાળા અનેક objects માટે constructor functions નો ઉપયોગ કરો.
સ્ત્રોત: 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
પોસ્ટ લિંક: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k