JavaScript માં Object Constructors
JavaScript constructors તમને કાર્યક્ષમ રીતે objects બનાવવા માટે મદદ કરે છે. તમે સમાન માળખાવાળા ઘણા objects બનાવવા માટે તેનો ઉપયોગ કરી શકો છો.
Constructor Functions
Constructor એ objects ને initialize કરવા માટેનું એક function છે. તેને call કરવા માટે new keyword નો ઉપયોગ કરો. જો તમે new keyword ભૂલી જશો, તો function અપેક્ષિત રીતે કામ કરશે નહીં.
હંમેશા constructor ના નામ મોટા અક્ષર (capital letter) થી શરૂ કરો. આ તમને તેમને સામાન્ય functions થી અલગ પાડવામાં મદદ કરે છે.
ઉદાહરણ:
- Person(name, age)
Object.create()
તમે અસ્તિત્વમાં રહેલા object ને prototype તરીકે ઉપયોગ કરીને નવું object બનાવવા માટે Object.create() નો ઉપયોગ કરી શકો છો. આ પદ્ધતિ objects વચ્ચે inheritance સેટ કરે છે.
Default Values
તમે તમારા constructor માં default values સેટ કરી શકો છો. આ સુનિશ્ચિત કરે છે કે તમારા objects માં હંમેશા માન્ય (valid) ડેટા હોય. જો તમે કોઈ value નહીં આપો, તો constructor default value નો ઉપયોગ કરશે.
ઉદાહરણ:
function Person(name = "Unknown", age = 0) {
this.name = name;
this.age = age;
}
Prototypes અને Memory
Prototype માં methods ઉમેરવાથી memory બચે છે. દરેક object પાસે function ની પોતાની કોપી હોવાને બદલે, તેઓ બધા prototype માંથી એક જ version શેર કરે છે.
ઉદાહરણ:
Person.prototype.greet = function() {
console.log("Hello " + this.name);
};
Inheritance
Classes એક class ને બીજી class માંથી inherit કરવાની મંજૂરી આપે છે. parent constructor ને call કરવા માટે super() keyword નો ઉપયોગ કરો. આ child classes ને parent classes માંથી properties અને methods વાપરવા દે છે.
Constructors નો ઉપયોગ શા માટે કરવો?
- Reusability: એક template માંથી ઘણા objects બનાવો.
- Organization: object setup logic ને એક જ જગ્યાએ રાખો.
- Initialization: બનાવતી વખતે જ ચોક્કસ values સેટ કરો.
- Inheritance: સરળ objects માંથી જટિલ (complex) objects બનાવો.
- Maintenance: તમારા code ને વાંચવામાં અને મેનેજ કરવામાં સરળ બનાવે છે.
Source: https://www.geeksforgeeks.org/javascript/js-constructor-method/ Source: https://www.w3schools.com/js/js_object_constructors.asp
Full post: https://dev.to/kamalesh_ar_6252544786997/object-constructors-in-javascript-2e96