1

So I've got a session variable, req.session.user, that contains an object corresponding to a user account. When I do this,

var user = req.session.user;
var fakeUser = user;
fakeUser.username = 'bob';

user.username and req.session.user.username both get changed to 'bob' as well. How do I prevent this?

user1816679
  • 845
  • 3
  • 11
  • 19

2 Answers2

0

When you write var fakeUser = user you copy reference to the object user - fakeUser is still referencing the same object.

If you want copy the object, you have to clone it or copy only desired properties of the user: e.g.:

var fakeUser = {
  name: user.name,
  id: user.id
}

JS clonning is described in following answers:

answer 1 answer 2

You can also use a clone method of underscore library (But be aware that it does just a shallow copy (not deep) - i.e. if user object contains some references, they are copied as references).

Simple method to clone object is to just serialize and deserilaze it (but this will not work on circular references - when object is referencing itself or it's part):

function clone(a) {
   return JSON.parse(JSON.stringify(a));
}
Community
  • 1
  • 1
lopisan
  • 7,720
  • 3
  • 37
  • 45
  • Could you explain cloning? – AliBZ May 14 '13 at 00:17
  • i've added a link to a question about clonning. Clonning means that you copy all properties of the object as values (primitive types are copied this way using = ), not just reference (objects are copied this way using = ). – lopisan May 14 '13 at 00:23
  • I know, but you will face problems if you are not the creator of the object. @zavg's answer is the right way to do. By explain I meant please say if there is a function to do that or you have to do it manually. Sorry, I wasn't clear. – AliBZ May 14 '13 at 00:25
  • I've added some links to answer. – lopisan May 14 '13 at 08:48
0

Clone it

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}
zavg
  • 10,351
  • 4
  • 44
  • 67