一起来手写 数据双向绑定、原生ajax、深拷贝

  • 手写数据双向绑定,vue实现双向绑定的原理就是Object.defineProperty,重写其中的get,set方法
<input id=txt />
<p id="show-txt"></p>

var obj={};
Object.defineProperty(obj,'txt',function(){
    get:function(){
        return obj;
    }
    set:function(newValue){
        document.getElementById("#txt").value=newValue;
        document.getElementById("#show-txt").innerHTML=newValue;
    }
});
document.addEventListener("keyup",function(e){
    obj.txt=e.target.value;
});

  • 手写一个原生ajax

首先分析一下创建ajax的过程

1.创建一个XMLHttpRequest对象

2.创建一个http请求,并指定请求的方法,URL

3.构造响应请求状态的函数

4.发送这个请求

5.获取异步调用回来的数据

6.通过js等将数据展现出来

var xhr=null;
if(window.XMLHttpRequest){
    xhr=new xmlHttpRequest();
}
else if(window.ActiveXObject){
    xhr=new ActiveXObject("Micosoft.XMLHTTP");
}
else{
    xhr=null:
}
if(xhr){
    xhr.open("GET",url);
    xhr.onreadyStatechange=function(){
    if(xhr.readystate==4&&xhr.status==200){
        console.log(xhr.data):
        }
        xhr=null;
    };
    xhr.send();
}

  • 手写一个深拷贝,深拷贝存在的原因:使用浅拷贝,若有引用类型的值,就容易导致错误
function deepClone(obj){
    var newobj=obj.instanceof Array?[]:{};
    if(typeof obj!=="object"){
    return obj;
    }
    else{
        for(var i in obj){
            newobj[i]=obj[i].typeof obj[i]=="object"?deepClone(obj[i]):obj[i];
        }
    }
return newobj;
}

类似的还有手写bind、promise。




猜你喜欢

转载自blog.csdn.net/weixin_41330202/article/details/80508549