Objects in JavaScript can exhibit some strange behavior, which may not always be what you expect.
When I create a new Object() and set properties within it, I assume that each time I create a new instance, the object would have its default values. However, instead of this, I find that the properties set in the previous instance are retained. It's frustrating!
The following example clearly illustrates this problem:
function testo() {}
testo.prototype = {
obj: {
what: {
value: 5
}
},
done: function () {
console.log(this.obj.what.value);
this.obj.what = {value: 10};
}
};
var x = new testo();
x.done();
var y = new testo();
y.done();
The output of the above code is:-
5
10
I had expected it to be:-
5
5
Why doesn't the output match my expectations? I thought that when creating a new instance of the Class() each object inside it should have its default properties without being affected by changes made in previous instances.
This example serves as a demonstration of the issue I am encountering in my library. I understand that it has to do with objects being stored as references.
How can I modify my approach to achieve the desired output? Any suggestions?