First, when you do this:
class Test {
constructor(data) {
this.foo = data; // [*]
}
//...
}
Doing this.foo = data;
does not make a copy of data
.
So, later, as you are using...
const initialData = { bar: [] };
...the same initialData
object on both instantiations:
const a = new Test(initialData);
const b = new Test(initialData);
...then both a
and b
are referencing the same object. So, naturally, when either of a
or b
modifies that object, it affects both.
This is how the language works and it's not really even related to classes or constructors or anything. Consider:
const data = { bar: [] };
const a = data;
const b = data;
a.bar.push(1);
Or...
const data = { bar: [] };
const a = {
foo: 'baz',
data: data
};
const b = {
foo: 'baz',
ble: data
};
a.data.qux = 'meh';
b.ble.bar.push(1);
When I make the assignment a = data
or when I do b = { /* ... */ ble: data }
, it's never making a copy of data
.
If you need to have your own copy of something, you'll need to actually make a copy of it.