JavaScript માં Factory Functions અને Constructor Functions

એક પછી એક objects બનાવવા એ એક ભૂલ છે.

જો તમારી પાસે 100 classmates હોય અને દરેક માટે એક object બનાવવાની જરૂર હોય, તો દરેક માટે અલગ-અલગ objects લખવાથી સમસ્યાઓ ઊભી થાય છે. તમારે તમારું logic વારંવાર લખવું પડે છે. આનાથી bugs આવવાનું જોખમ પણ રહે છે. ઉદાહરણ તરીકે, તમે કદાચ તમારા કોડમાં પછીથી ભૂલથી કોઈ property નું નામ બદલી (overwrite) શકો છો.

તમારે logic ને reuse કરવા માટે વધુ સારી રીતની જરૂર છે.

Factory Functions એક factory વિશે વિચારો. તમે કાચો માલ નાખો છો અને તૈયાર ઉત્પાદન મેળવો છો. Factory function પણ આવું જ કરે છે. તે parameters લે છે અને એક નવો object return કરે છે.

Example:

function classFactory(name) {
    return {
        reply() {
            return `${name} is present`
        }
    }
}

આ અભિગમ નામ સુરક્ષિત રાખે છે. તમે ભૂલથી પણ નામ બદલી શકતા નથી કારણ કે તે function scope ની અંદર રહે છે. તમે logic એકવાર લખો છો અને તેનો ઘણી વખત ઉપયોગ કરી શકો છો.

Constructor Functions Constructor functions પણ objects બનાવે છે. તેઓ this keyword અને new keyword નો ઉપયોગ કરે છે. પરંપરાગત રીતે, આ functions મોટા અક્ષર (capital letter) થી શરૂ થાય છે.

Example:

function Classmate(name) {
    this.name = name
    this.reply = function() {
        return `${this.name} is present`
    }
}

જ્યારે તમે new keyword નો ઉપયોગ કરો છો, ત્યારે JavaScript તમારા માટે કામ કરે છે. તે એક નવો object બનાવે છે, તેને this ને assign કરે છે, અને તેને આપમેળે return કરે છે. તમારે return statement ની જરૂર નથી.

Scaling your code તમે મોટા પ્રમાણમાં ડેટા હેન્ડલ કરવા માટે આ પદ્ધતિઓને arrays સાથે જોડી શકો છો.

const names = ['Kali', 'Andrew', 'Pearl', 'Percy']
const classmates = names.map(name => new Classmate(name))

classmates.forEach(c => console.log(c.reply()))

આ તમારા કોડને clean અને scalable બનાવે છે.

મુખ્ય ધ્યેય સરળ છે:

Source: https://dev.to/pearlodi/factory-functions-and-constructor-functions-in-javascript-lmb