Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'd make a function that returns an object with the desired properties (created anew every time the function creates a new object):

const makeObj = () => {
  const protoObj = {
    myPrim: false,
    myDict: {},
    changePrim: function(val) {
      this.myPrim = val;
    },
    addToDict: function(val) {
      this.myDict[val] = val;
    }
  };
  return Object.create(protoObj);
}

const myObj2 = makeObj();
myObj2.changePrim(true);
myObj2.addToDict("test");
const myObj3 = makeObj();
console.log(myObj3.myDict);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...