简体   繁体   中英

Javascript clone variable without reference

I have two variables that keep track of session information. One of the variables has timeout functions while the other does not (for sending to the cache).

I start off by creating the variables:

//Save Session
sessions.data[sid] = {
    'sid':          sid,
    'socket':       null,
    'timeout':      null
};


//Cache Data
sessions.saved[sid] = { 'sid':sid };

//Save Cache
system.cache.save('sessions', sessions.saved);


//Begin Timeout
sessions.data[sid].timeout = this.timeout.start( sessions.data[sid] );

//Callback
callback( sessions.data[sid] );

More variables are added and returned to a save: function(session) :

//Overwrite session
sessions.data[session.sid]          = session;

//Duplicate Session
sessions.saved[session.sid]         = $.extend(true,{},session);

//Clear Duplicate Timeout
clearTimeout( sessions.saved[session.sid].timeout );

//Set Values to Null
sessions.saved[session.sid].timeout     = null;
sessions.saved[session.sid].socket      = null;

//Save Cache
system.cache.save('sessions', sessions.saved);

The issue is both variables (sessions.saved && sessions.data) will have timeout: null . I have been reading through other articles about how to stop it from passing by reference but can't seem to get it to work. I've read a bunch of articles like: Clone Object without reference javascript but can't get it to work. I've also tried to set it with its own variable:

var unreferenced                    = $.extend(true,{},session);
sessions.saved[session.sid]         = unreferenced;

but I get the same result. Any help is greatly appreciated :)

Turns out it was a completely different variable that was creating the reference when the page loaded:

system.cache.get('sessions',function(cache){
    if(cache !== null){
        sessions.data   = JSON.parse(cache);
        sessions.saved  = sessions.data;

        //Set new Timeouts, Log inactive users out
        for(var key in sessions.data){
            sessions.data[key].timeout = sessions.timeout.start( sessions.data[key] );
        }
    }
});

A little oversight and 2 hours of head-scratching!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM