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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With