手写instanceof和深拷贝

instanceof

//基本思路就是利用循环在原型链上查找看是否符合
function myInstanceof(left,right){
    let proto=left.__proto__;
    let prototype=right.prototype;
    
    while(true){
        if(proto===null) return false;
        if(proto===prototype) return true;
        proto=proto.__proto__;
    }
}

深拷贝

//需要考虑多种情况,核心代码是递归
function deepClone(obj,hash=new WeakMap()){
    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 cloneObj=new obj.constructor();//开辟空间
    if(hash.get(obj)) return hash.get(obj);//避免循环引用
    hash.set(obj,cloneObj);
    
    for(let key in obj){
        //for in 会将原型上的属性遍历,这不是我们期望的
        if(obj.hasOwnProperty(key)){
            cloneObj[key]=deepClone(obj[key],hash);
        }
    }
    return cloneObj;
}


#我的秋招日记#
全部评论
冒昧的问下,你这啥语言
点赞 回复 分享
发布于 2022-07-27 13:15

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务