简体   繁体   English

Javascript Object。创建对对象的复制引用

[英]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. 我有从ViewModel继承的对象,并且它们都具有更新功能。 I have an array, that I'm updating with new stuff from a json object (initial). 我有一个数组,正在使用json对象(初始)中的新内容进行更新。 Sometime the Json object is longer than the existing array I'm updating, so I want to add objects of the same type. 有时Json对象比我要更新的现有数组长,因此我想添加相同类型的对象。 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. 我正在使用Object.create(this [key] [ittr -1])指向数组中的最后一个对象,并尝试从中实例化一个新对象。 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 我也尝试过jQuery

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

I've tried making x into an array 我试过将x变成数组

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. 每当我调用x.update时,它都会更改已设置为等于x的数组中的每个值。 So I'm never actually making a new object when I call Object.create 因此,当我调用Object.create时,我从来没有真正制作过新对象

Well, the first argument to Object.create is the object you want to be the prototype of the newly created object. 好吧, Object.create的第一个参数是您想要成为新创建对象原型的对象。 See MDN . 参见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. 尝试将ViewModel.prototype作为第一个参数传递,并将旧对象作为第二个参数传递。 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. 扩展路由不会完全成功,因为新对象将具有旧对象的所有属性,但它不会继承自ViewModel.prototype ,因此不会具有更新或任何其他原型方法/属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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