手写浅拷贝

记录贴

 

// 手写浅拷贝
    let arr = [1,2,3,4,5]
    let obj = {
        name:1
    }
    function My(){
        this.age = 0
        
        My.prototype.nes = function(){
            console.log("哈哈")
        }
    }
    
    let Obj = new My()
    // assing
    let news = Object.assign({},obj)
    news.name = 132
    console.log(news,obj)
    //Array.concat;Array.slice;[...Array]
    
    
    console.log(shallowCopy(Obj))
    
    function type(data){
        let    datas = Object.prototype.toString.call(data).slice(8,-1)
        return datas
    }
    
    function shallowCopy(target){
        let result = type(target) == "Object"?{}:[]
        for(let e in target){
            if(target.hasOwnProperty(e)){
                if(typeof target[e] === "object"){
                    if(target[e] === null){
                        result[e] = null
                    }else{
                        shallowCopy(target[e])
                    }
                }else{
                    result[e] = target[e]
                }
            }
        }
        return result
    }

 

posted @ 2020-12-26 17:31  JS-Feng  阅读(104)  评论(0编辑  收藏  举报