I'm creating an object to be used as a prototype for other objects. This object contains primitives as well as a series of dictionaries. My problem is that when the dictionary properties are edited through one of the object's methods, it edits the dictionary in the object prototype, instead of the dictionary in the specific object instance.
For example:
const protoObj= {
myPrim: false,
myDict: {},
changePrim: function(val) {
this.myPrim = val;
},
addToDict: function(val) {
this.myDict[val] = val;
}
};
const myObj2 = Object.create(protoObj);
myObj2.changePrim(true);
myObj2.addToDict("test");
const myObj3 = Object.create(protoObj);
At this point myObj2.myPrim
is true, and myObj3.myPrim
is false. But the addToDict method added the "test" entry to the myDict of the prototype object, so now myDict has been essentially modified for both myObj2 and myObj3.
How could I make it such that actions on the dictionary member only affect the specific object instance?
question from:https://stackoverflow.com/questions/65649760/object-createmyobj-when-myobj-contains-dictionaries