简体   繁体   中英

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.

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. 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.

Second there is a property

ownerDocument 

So you are looping over that...

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