为什么jQuery Extend Deep Copy不能递归复制对象? [英] Why does jQuery Extend Deep Copy not recursively copy an object?

查看:102
本文介绍了为什么jQuery Extend Deep Copy不能递归复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索,发现类似的问题,答案并没有真正解决我的问题所以我道歉,如果这似乎是重复,但从我的实验中看来,jQuery的深拷贝功能实际上并不起作用,因为它是描述(或者我可能误读了它的描述)。

I've searched everywhere and found similar questions with answers that didn't really address my issue so I apologize if this seems like a repeat, but it appears from my experimenting that jQuery's deep copy function doesn't actually work as it's described (or maybe I'm misreading its description).

这是一个展示我遇到的问题的例子:
http://jsfiddle.net/wcYsH/

Here's an example demonstrating the problem I'm having: http://jsfiddle.net/wcYsH/

或者这个下载:
https://github.com/kevroy314/jQuery-Extend-Test

为什么操作深层副本时前一个副本中的数据会被更改?

Why does the data in the previous copy get changed when the deep copy is manipulated?

推荐答案

首先,你不是在创建普通对象。

For one, you aren't creating normal objects.

我正在查看jQuery 1.7.2 for extend的源代码。

I'm looking at the source code for jQuery 1.7.2 for extend.

https://github.com/jquery/jquery/blob/master/src/core.js

我注意到这一行:

if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy))

必须评估为 true 进行深度复制。复制只是当前被复制对象的一部分。

has to evaluate to true to do deep copying. copy is just part of the current object being copied.

但你不是你正在创建普通对象。你正在创建通过使用new运算符调用构造函数生成的对象。

But you aren't creating "plain" objects. You are creating objects generated by invoking a constructor with the new operator.

现在,在isPlainObject中,似乎必须对这些行进行求值。(其中hasOwn是​​ hasOwn = Object.prototype.hasOwnProperty

Now, in isPlainObject, it seems these lines have to be evaluated. (where hasOwn is hasOwn = Object.prototype.hasOwnProperty

    try {
        // Not own constructor property must be Object
        if ( obj.constructor &&
            !hasOwn.call(obj, "constructor") &&
            !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
            return false;
        }
    } catch ( e ) {
        // IE8,9 Will throw exceptions on certain host objects #9897
        return false;
    }

并且它的结论是它不是plainObject。

And there's where it concludes it's not a "plainObject".

当您考虑使用构造函数的对象可能应该通过该构造函数创建或者至少使用某种clone时,这是有意义的您可以在其他语言/框架中看到的方法。

This makes sense when you consider objects with a constructor probably ought to be created via that constructor or at least use some sort of "clone" method as you'd see in other languages/frameworks.

这篇关于为什么jQuery Extend Deep Copy不能递归复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆