Search code examples
javascriptobjectdeep-copy

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?


Solution

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