Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I would like to ask why nodejs variables are affected even though they are not global variables?

// my router.js 
var express = require('express');
...
...
var async   = require('async');
var sboard  = require('../lib/sboard.js');

router.get('/shop/list/',async function(req,res,next){
    //var url_parse = url.parse(cfg.url_full);
    //cfg.url_query = url_parse.query;;
    var data        = await sboard.get_list(req); 
    var main_arr    = templateSboardList.MAIN(data);
    var main_body   = main_arr['body'];
    var main_js     = main_arr['js'];
    var main_title  = main_arr['title'];
    commonTemplate.PAGEBODY(req,res,next,main_title,main_body,main_js,db,function(result){
        res.send(result);
    });

// my /lib/sboard.js
// return result ['page=1&btype=mk', { page: '1', btype: 'mk' }]
get_qstr:function(req){
    var qstr = [];
    var qstr_obj = {};
    if(typeof req.query.page !== 'undefined'){ 
        qstr.push(['page='+req.query.page]);
        qstr_obj['page'] = req.query.page;
    }
    if(typeof req.query.btype !== 'undefined'){ 
        qstr.push(['btype='+req.query.btype]);
        qstr_obj['btype'] = req.query.btype;
    }
    if(typeof req.query.btype_sub !== 'undefined'){ 
        qstr.push(['btype_sub='+req.query.btype_sub]);
        qstr_obj['btype_sub'] = req.query.btype_sub;
    }
    if(typeof req.query.search_keyword !== 'undefined'){ 
        qstr.push(['search_keyword='+req.query.search_keyword]);
        qstr_obj['search_keyword'] = req.query.search_keyword;      
    }
    return [qstr.join('&'),qstr_obj];
},
get_qstr_filter:function(data,items){
    if(data[0].length){
        var new_data = data[0].split('&');
        data[0] = [];
        for(var i in new_data){
            var v = new_data[i].split('=');
            if(!in_array(v[0],items)){
                data[0].push([v[0]+'='+v[1]]);
            }
        }
        data[0] = data[0].join('&');
    }
    if(Object.keys(data[1]).length){
        for(var i in data[1]){
            for(var ii in items){
                delete(data[1][items[ii]]);
            }
        }
    }
    var v = data
    return v;
}, 

get_list:async function(req){
var cfg = {
        btype:typeof req.query.btype!=='undefined'?req.query.btype:'mk',
        btype_sub:typeof req.query.btype_sub!=='undefined'?req.query.btype_sub:'board',
        page_current: typeof req.query.page == 'undefined'?1:parseInt(req.query.page),
        page_limit:5,
        search_keyword:typeof req.query.search_keyword!=='undefined'?req.query.search_keyword:'',
        url_full:req.protocol + '://' + req.get('host') + req.originalUrl,
        url_qstr:this.get_qstr(req)
    }


// result log [ 'page=1&btype=mk', { page: '1', btype: 'mk' } ]
console.log('aaa',cfg.url_qstr); 

// result log [ 'btype=mk', { btype: 'mk' } ]
console.log('bbb',this.get_qstr_filter(cfg.url_qstr,['page'])[1]); 

// result log [ 'btype=mk', { btype: 'mk' } ]
console.log('ccc',cfg.url_qstr);

}

In the console.log ccc section,
why is the value of cfg set to the return value when calling get_qstr_filter?

the result of my thoughts console.log ccc section
result log [ ‘page=1&btype=mk’, { page: ‘1’, btype: ‘mk’ } ]

Shouldn’t it have the same value as the console.log aaa section?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why does the cfg value change in the ccc section
after calling the function?

Why are variables initialized with the function’s return value after calling the function? cfg is not a global variable.

>Solution :

Arrays in JS are objects. e.g typeof [] == 'object'

Objects get passed by reference. Meaning, when you pass an object (or in this case array) in a function parameter, you are passing a reference to the object, and not a copied value. Any changes to the reference will reflect in all the places it is referenced (e.g. in the cfg object instance).

In your code, this.get_qstr_filter(cfg.url_qstr,['page'])[1]) is passing the reference to the array, so when data argument is mutated, it is (also) mutating the original (referenced in the cfg object).

Another way to put it: data argument in this case is not a local variable holding a copy of the cfg.url_qstr array, it’s a local variable holding a reference to the cfg.url_qstr array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading