JavaScript实现对象深拷贝的方式(包含函数克隆)

时间:2020-11-21
本文章向大家介绍JavaScript实现对象深拷贝的方式(包含函数克隆),主要包括JavaScript实现对象深拷贝的方式(包含函数克隆)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 //创建一个对象
let s={
        name:'yds',
        age:21,
        data:{
            p:'ws',
            sys:'root'
        },
        arr:[12,56,78],
        fn:function(){
            console.log('嗨')
        }
    };

//自定义一个深拷贝递归函数
 function deepClone(obj){
        let clone = Array.isArray(s)?[]:{};
        for (const key in obj) {
            let item = obj[key];
            if(item){
                //实现方法的克隆
                if(item instanceof Function){
                    clone[key] = new Function('return '+item.toString())()
                }
                else if(item instanceof Object ){
                    clone[key] = deepClone(item);
                }
                else {
                    clone[key] = item;
                }
            }
        }
        return clone;
    }
 
 //可以实现复杂的深拷贝,但无法克隆函数
    //let clone = JSON.parse(JSON.stringify(s));
    //无法实现复杂的深拷贝,对于复杂对象只复制其引用
    //let clone = {...s}
    //自定义递归 实现了函数的克隆
    let clone = deepClone(s);
    s.name = 'hmy';
    s.data.p='ms';
    console.log(s);
    console.log(clone);
    clone.fn();

  控制台输出:

{name: 'hmy', age: 21, data: {…}, arr: Array(3), fn: ƒ}
{name: 'yds', age: 21, data: {…}, arr: {…}, fn: ƒ}

原文地址:https://www.cnblogs.com/TaranZhu/p/14017580.html