1.实现原生的AJAX请求
const ajax = {
get(url, fn) {
const xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
fn(xhr.responeText)
}
}
xhr.send()
},
post(url, data, fn){
const xhr = new XMLHttpRequest()
xhr.open('post', url, true)
xhr.setRequestHeader{'Content-type','application/x-www-form-urlencoded'}
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
fn(xhr.responeText)
}
}
xhr.send(data)
}
}
2.手写new的过程
function instanceOf(father, child){
const fp = father.prototype
var cp = child.__proto__
while(cp){
if(cp === fp){
return true
}
cp = cp.__proto__
}
return false
}
3.实现防抖函数
function debounce(fn, delay = 500){
let timer;
return function(){
if (timer){
clearTimeout(timer)
}
const args = arguments
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
4.实现JSON.parse
function parse(json){
return eval("(" + json + ")");
}
5.将DOM转化成树结构对象
function dom2tree(dom){
const obj = {}
obj.tag = dom.tagName
obj.children = []
dom.childNodes.forEach(child => obj.children.push(dom2tree(child)))
return obj
}