JS中深克隆与浅克隆简单实现

129 阅读1分钟

浅克隆

    let obj1={
        name:'zs',
        arr:[1,[2,3],4],
        foo:{
            color:'red',
            ask:(res)=>{
                console.log(res)
            }
        }
    }
    function clone(source) {
        let cloneObj = {};
        for (const key in source) {
            if (Object.hasOwnProperty.call(source, key)) {
                const element = source[key];
                cloneObj[key] = element;
            }
        }
        return cloneObj;
    }
    let obj2 = clone(obj1);
    console.log(obj2.arr===obj1.arr) //true
    

深克隆

    let obj1={
        name:'zs',
        arr:[1,[2,3],4],
        foo:{
            color:'red',
            ask:(res)=>{
                console.log(res)
            }
        }
    }
    function deepClone(obj){
        if(obj===null){
            return obj
        }
        if(obj instanceof Date){
            return new Date(obj)
        }
        if(obj instanceof RegExp){
            return new Regexp(obj)
        }
        if(typeof obj !== 'object'){
            return obj
        }
        let newObj=new obj.constructor()
        for (const key in obj) {
            if (Object.hasOwnProperty.call(obj, key)) {
                newObj[key]=deepClone(obj[key])
            }
        }
        return newObj
    }
    let test=deepClone(obj1)
    console.log(obj1.arr===test.arr)  //false