简体   繁体   中英

Javascript Object.Create copying reference to object

I have the following code

ViewModel.prototype.update = function(initial) {
  var ittr, key, val, x;
  for (key in initial) {
    val = initial[key];
    if ($.isArray(val) && $.isArray(this[key]())) {
      ittr = 0;
      while (ittr < val.length) {
        if (this[key].length > ittr) {
          if ((this[key][ittr - 1]) instanceof ViewModel) {
              x = Object.create(this[key][ittr - 1]);
              x.update(val[ittr]);
              this[key].push(x);
          }
        }
      }
    }
  }
}

I have objects inheriting from ViewModel, and they all have update as a function. I have an array, that I'm updating with new stuff from a json object (initial). Sometime the Json object is longer than the existing array I'm updating, so I want to add objects of the same type. I'm using Object.create(this[key][ittr -1]) which points to the last object in the array, and it tries to instantiate a new object from that. The problem is, every iteration, it doesn't create a new object, but it's just a copy of the old one. Any idea how I can stop that?

I've tried jquery as well

new $.extend({},this[key][ittr - 1])

I've tried making x into an array

x[ittr] = Object.create(this[key][ittr - 1]);
x[ittr].update(val[ittr]);
this[key].push(x[ittr]);

When ever I call x.update, it changes every value in the array which has been set equal to x. So I'm never actually making a new object when I call Object.create

Well, the first argument to Object.create is the object you want to be the prototype of the newly created object. See MDN . Essentially, it will be a new object, but it will look like the old object because it inherits all the properties of the old object via it's prototype. Try passing ViewModel.prototype as the first argument, and the old object as the second argument. The extend route won't be completely successful, as the new object will have all of the properties of the old object except it will not inherit from ViewModel.prototype , and thus won't have update or any other prototype methods/properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM