Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new object, not a reference [duplicate]

Tags:

javascript

this is my first time here.

So the problem is, i have an object with all my variables like this:

app.Variables = {
    var1: 0,
    var2: 0,
    var3: 0
}

And i want to store this values in a object called Defaults like this:

app.Defaults = app.Variables

But the problem now is, in my code, app.Variables.var1 e.g. get incremented like this:

app.Variables.var1++

And this means, that app.Defaults.var1 get also incremented equal to app.Variables.var1.

What shall i do here?

like image 201
DerToti Avatar asked Oct 22 '22 06:10

DerToti


1 Answers

Simplest version is to use JSON.parse/stringify, fastest is to use a plain clone method:

/* simplest */
var clone = JSON.parse(JSON.stringify(obj));

/* fastest */
function clone(obj) {
    if (obj == null ||typeof obj != "object") return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}
var clone2 = clone(obj);
like image 98
Christoph Avatar answered Oct 23 '22 22:10

Christoph