jQuery.从循环引用扩展safe

Is jQuery.extend safe from circular reference?

本文关键字:扩展 safe 引用 循环 jQuery      更新时间:2023-09-26

jQuery.extendcircular reference安全吗?

如何避免在Javascript循环引用(而克隆或递归检查)?仅仅在属性列表中检查当前目标是否存在是不够的,因为它可能引用一些外部对象。

一个选项是保留另一个列表的所有objects获取到现在。但是这会增加内存消耗并要求停止脚本吗?

和我不想移动克隆操作在工作线程

老问题,但我今天正在寻找这个-答案是:没有。

https://api.jquery.com/jquery.extend/

在深度扩展上,对象和数组被扩展,但是对象包装在基本类型上而String、Boolean和Number则不是。深度扩展循环数据结构将导致错误

对于超出此行为的需求,编写自定义扩展方法,或者使用lodash等库。

lodash文档不是很清楚,但是_。cloneDeep支持克隆循环引用。

https://lodash.com/docs/4.17.10 cloneDeep

你最好使用像lodash这样聪明的东西,因为我认为它会正确地检测多次引用的所有对象,并创建整个对象图的真正克隆,所有循环引用都完好无损。

然而,这里有一个简单的深度克隆,它只是使用一个简单的对象堆栈来忽略循环引用(它在TypeScript中):

public static DeepClone(source: any, stack: any[] = null): any
{
    if (!source)
    {
        return source;
    }
    var result;
    result = Array.isArray(source) ? [] : {};
    for (var k in source)
    {
        var v = source[k];
        if (typeof v === "object") 
        {
            stack = stack || [];
            // Just ignore circular references? Or, to be clever, maintain a 
            // dictionary of object references from the original graph linked to
            // the new objects in the cloned graph, to preserve the full graph.
            if (stack.indexOf(source) >= 0)
            {
                return null;
            }
            stack.push(source);
            result[k] = this.DeepClone(v, stack);
            stack.pop();
        }
        else
        {
            result[k] = v;
        }
    }
    return result;
}