20170606-浅拷贝与深拷贝

什么是深拷贝,什么是浅拷贝

JS中的浅拷贝与深拷贝是针对庞杂数据范例(援用范例)的复制题目。

  • 浅拷贝:浅拷贝是拷贝援用(拷贝地点),拷贝后两个变量指向的是统一块内存空间

  • 深拷贝:会在内存中拓荒一块新的内存空间,它不仅将原对象的各个属性逐一复制过去,而且将原对象各个属性所包括的内容也顺次采纳深复制的要领递归复制到新的内存空间中,并把新的内存空间的地点复制给第二个变量,这两个变量指向的是差别的对象,两个变量的任何操纵都不会影响到对方

完成深拷贝的经常使用要领

1.JSON.parse(JSON.stringify(object))

2. 递归完成深拷贝

function deepCopy(obj){
    if(typeof obj !== 'object'){
        return obj
    }
    var temp = new Object()
    for(var i in obj){
        if(typeof obj[i] === 'object'){
            temp[i] = arguments.callee(obj[i])
        }else {
            temp[i] = obj[i]
        }
    }
    return temp
}

这个要领能正确处置惩罚的对象只要 Number, String, Boolean, Array, 扁平对象,即那些可以被 json 直接示意的数据结构。

3. 经由过程jQuery的extend要领

var CopyObject = $.extend(true, {}, object)

源码剖析

jQuery.extend = jQuery.fn.extend = function() {
    var src, copyIsArray, copy, name, options, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // 假如第一个参数是布尔范例的,申明指定了是不是要举行深拷贝,则第二个参数指的是目的对象
    if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {
        // options为源对象
        if ( (options = arguments[ i ]) != null ) {
            
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // 处置惩罚纯对象和数组
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                  
                    if ( copyIsArray ) {
                        // 被拷贝的对象是数组时
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        // 被拷贝对象是对象
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // 递归挪用extend要领,完成该属性的深拷贝
                    target[ name ] = jQuery.extend( deep, clone, copy );

                
                } else if ( copy !== undefined ) {
                    // 假如属性是简朴数据范例,直接复制
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};
    原文作者:jhhfft
    原文地址: https://segmentfault.com/a/1190000009678995
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞