对象赋值无限递归

对象赋值无限递归

本文介绍了Javascript 对象赋值无限递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我难以理解的问题.任何帮助将不胜感激.

I have an issue that I am struggling to grasp. Any help would be greatly appreciated.

我有一个对象,我将当前对象状态分配给当前对象的一个​​属性.

I have an Object, and I assign the current object state to a property on the current object.

示例如下:

var product = {
  ropeType: 'blah',
  ropePrice: 'blah',
  ropeSections: {
    name: 'blaah',
    price: 'blaah'
  },
  memory: false
}

product.memory = product;

现在,当我在控制台中查看产品对象时,我得到了 Product.memory.Product.memory.Product 的无限递归......

Now when I look at the product object within the console I get a inifinite recursion of Product.memory.Product.memory.Product....

截图如下:

我知道这与对象引用自身有关,但我似乎无法理解这个概念.有人能解释一下吗?

I know its something to do with that an object references itself, but I cannot seem to grasp the concept. Could someone explain?

我尝试这样做的原因是将对象的当前状态保存在本地存储中.

The reason I am trying to do something like this is to save in local storage the current state of the object.

我希望我说得有道理.

推荐答案

不,您创建了一个引用自身的属性.

No, you created a property that referred to itself.

如果要保存属性的当前状态,则需要克隆该对象.

If you want to save the current state of the property then you need to clone the object.

如果你想创建一个对象的(浅)副本,那么你可以使用:

If you want to create a (shallow) copy of an object then you can use:

function clone(obj) {
    if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    var temp = obj.constructor();

    for(var key in obj) {
        if(Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = obj[key];
            delete obj['isActiveClone'];
        }
    }

    return temp;
}

[取自此处的代码 - 稍作修改以进行浅拷贝而不是递归深拷贝]

[code taken from here - and modified slightly to do a shallow copy rather than recursive deep copy]

然后做:

product.memory = clone( product );

如果您第二次克隆它并且它将product.memory 与对象的其余部分一起复制,您可能会发现递归问题.在这种情况下,只需在进行后续克隆之前delete product.memory.

You may find you get the issues with recursion if you clone it a second time and it copies the product.memory along with the rest of the object. In that case just delete product.memory before doing subsequent clones.

类似于:

function saveCurrentState( obj ){
  if ( 'memory' in obj )
    delete obj.memory;
   obj.memory = clone( obj );
}

旁边

如果你想要一个深拷贝,那么你可以这样做:

If you want a deep copy then you can do:

function deepCopy(obj){
  return JSON.parse(JSON.stringify(obj));
}

[如此处所建议 - 但请注意它对 Date 对象的警告]

[As suggested here - but note the caveats it has for Date objects]

这篇关于Javascript 对象赋值无限递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:34