Javascript对象。创建对对象的复制引用
我有以下代码Javascript对象。创建对对象的复制引用,javascript,object,new-operator,object-create,Javascript,Object,New Operator,Object Create,我有以下代码 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) {
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);
}
}
}
}
}
}
我试着把x做成一个数组
x[ittr] = Object.create(this[key][ittr - 1]);
x[ittr].update(val[ittr]);
this[key].push(x[ittr]);
每当我调用x.update时,它都会更改数组中设置为x的每个值。因此,当我调用object时,我从来没有真正创建过一个新对象。create好吧,
对象的第一个参数。create
是您希望成为新创建对象原型的对象。看见从本质上讲,它将是一个新对象,但它看起来像旧对象,因为它通过原型继承了旧对象的所有属性。尝试将ViewModel.prototype
作为第一个参数传递,将旧对象作为第二个参数传递。扩展路径不会完全成功,因为新对象将具有旧对象的所有属性,除了它不会继承自ViewModel.prototype
,因此不会有更新或任何其他原型方法/属性。没有对象.prototype.create
x[ittr] = Object.create(this[key][ittr - 1]);
x[ittr].update(val[ittr]);
this[key].push(x[ittr]);