简体   繁体   English

JavaScript:深度复制Image()对象

[英]JavaScript: Deep Copy Image() Object

I have this object merging function: 我有此对象合并功能:

function merge( obj1, obj2 )
{
    var result = {};
    for( var prop in obj1 )
    {
        if( obj2.hasOwnProperty(prop) )
        {
            if( 'object' === typeof obj1[prop] && 'object' === typeof obj2[prop] )
            {
                result[prop] = merge( obj1[prop], obj2[prop] );
            }
            else
            {
                result[prop] = obj2[prop];
            }
        }
        else
        {
            result[prop] = obj1[prop];
        }
    }
    return result;
};

The purpose of this function is to merge two objects into one, overriding the values of obj1 with those of obj2, if exists. 此功能的目的是将两个对象合并为一个,如果存在,则用obj2的值覆盖obj1的值。

It works fine with most objects, however when I try to use it to merge two Image() objects, I'm thrown into an infinite loop. 它适用于大多数对象,但是当我尝试使用它合并两个Image()对象时,我陷入了无限循环。 For example: 例如:

merge(new Image(), new Image())

results in: 结果是:

Uncaught RangeError: Maximum call stack size exceeded

I think it has something to do with the object's events, but I'm not sure. 我认为这与对象的事件有关,但我不确定。 Why do you think this is this happening, and how can this function be improved to fix this issue? 您为什么认为这是这种情况,如何改进此功能以解决此问题?

First thing is null is an object so you are calling merge for all the nulls. 首先是null是一个对象,因此您要为所有null调用merge。

Second there is a property 第二有财产

ownerDocument 

So you are looping over that... 所以您正在遍历...

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

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