我怎样才能复制jQuery扩展?

时间:2013-12-22 22:08:36

标签: javascript jquery

我正在尝试实现jQuery的extend方法。然后我复制并改编了源:

function extend(deep, target, source)
{
    var copy, original, clone;
    for (var attr in source)
    {
        copy = target[attr];
        original = source[attr];

        if (target === original)
        {
            continue;
        }

        if (deep && original && typeof(original) === "object")
        {
            if (original instanceof Array)
            {
                clone = copy && (copy instanceof Array) ? copy : [];
            }
            else
            {
                clone = copy ? copy : {};
            }

            target[attr] = extend(deep, clone, original);
        }
        else if (original !== undefined)
        {
            target[attr] = original;
        }
    }

    return target;
}

然而,这是一个

  

RangeError:超出最大调用堆栈大小

虽然jQuery方法没有,但对于以下代码:

function Person( params) {
    this.id = params['id'];
    this.name = params['name'];
    this.father = null;
    this.toString = function() { return this.name };
}

var me = new Person({ id: 1, name: 'Luke'});
var him = new Person({ id:2, name: 'Darth'});
me.father = him; 
him.father = me; // time travel assumed :-)

var jQueryCopy = $.extend(true, {}, him); // ok
var copy = extend(true, {}, me); // exception

请参阅此example on jsFiddle

为什么我的方法抛出此异常而jQuery方法不是?

0 个答案:

没有答案