Javascript 如何复制jQuery扩展?

Javascript 如何复制jQuery扩展?,javascript,jquery,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) {

我正在尝试实现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
看这个


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

堆栈溢出(hah)。您的最终条件不正确。你需要保留一个你以前扩展过的属性列表,以防止循环引用。。。我不知道到底出了什么问题,这就是为什么我问。。。现在解决了。