I'm sorry for the low quality title but I don't know how to make it better (edits are welcome).
Look at this code example:
var a = {b: 1};
var c = {d: a, e: a};
c.d.b = 2;
alert(c.e.b); // 2 not 1
Like you can see in that code the result is 2
but I want it to be 1
. It seems that my nestled dictionaries are sharing the same space in memory, but I want to "fix" that.
Obviously the easiest solution would not have any a
dictionary.
var c = {d: {b: 1}, e: {b: 1}};
But I don't want this solution because I have to write several times {b: 1}
.
Then I developed two solutions but I want to know which of them is better, or if there is something better even.
Class
class a { // or -> var a = class { //?
constructor() {
this.b = 1;
}
}
var c = {d: new a(), e: new a()};
Function
function a() { // or -> var a = function() { //?
return {b: 1};
}
var c = {d: a(), e: a()};
Which of both is better? Or maybe any of both and the answer is another?