JS常见手写代码题(二)

2020-08-21  本文已影响0人  kugua666

1、用闭包手写一个cache工具

function creatCache() {
    let data = {} //隐藏数据,外部访问不到
    return {
        get(key) {
            return data[key]
        },
        set(key, val) {
            data[key] = val
        }
    }
}
var c = creatCache()
c.set('name', 'jin')
console.log(c.get('name'))

2、手写一个简易的JQuery,考虑插件和扩展性

class JQuery {
    constructor(selector) {
        const result = document.querySelectorAll(selector)
        const length = result.length
        for (let i = 0; i < length; i++) {
            this[i] = result[i] //因为i是变量就用[]的方式
        }
        this.length = length
        this.selector = selector
    }
    get(index) {
        return index
    }
    each(fn) {
        for (let i = 0; i < this.length; i++) {
            const element = this[i]
            fn(element)
        }
    }
    on(type, fn) {
        return this.each(element => {
            element.addEventListener(type, fn, false)
        })
    }
}
//插件扩展性
JQuery.prototype.dialog = function (info) {
    alert(info)
}
//造轮子
class myJQery extends JQuery {
    constructor(selector) {
        super(selector)
    }
    //扩展自己的方法
    addClass(className) {}
    style(data) {}
}

3、手写Promise加载一张图片

function loadImg(src) {
    return new Promise(
        (resolve, reject) => {
            const img = document.createElement('p')
            img.onload = () => { //onload事件是当图片加载完成之后再触发事件
                resolve(img)
            }
            img.onerror = () = { //onerror事件是当图片加载出现错误,会触发事件
                reject(err)
            }
            img.src
        }
    )
}
//先加载第一张图片,再加载第二张
const url1 = ' '
const url2 = ' '
loadImg(url1).then(img1 => {
    console.log(img1.width)
    return img1
}).then(img1 => {
    console.log(img1.height)
    return loadImg(url2)
}).then(img2 => {
    console.log(img2.width)
    return img2
}).then(img2 => {
    console.log(img2.height)
})

4、手写一个简易的ajax
(1)get请求的ajax

let xhr = new XMLHttpRequest() //1、创建连接
xhr.open('GET', url, true) //2、连接服务器
xhr.onreadystatechange = function () { //4、接收请求,当状态改变时触发这个函数
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {//xhr.responseText是字符串需转换为JSON
            success(JSON.parse(xhr.responseText))
        } else {
            fail(xhr.status)
        }
    }
}
xhr.send(null) //3、发送请求

(2)post请求的ajax

let xhr = new XMLHttpRequest() //1、创建连接
const postData = {
    userName: 'zhangshan',
    passWord: 'xxx'
}
xhr.open('POST', url, true) //2、连接服务器
xhr.onreadystatechange = function () { //4、接收请求,当状态改变时触发这个函数
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {//xhr.responseText是字符串需转换为JSON
            success(JSON.parse(xhr.responseText))
        } else {
            fail(xhr.status)
        }
    }
}
xhr.send(JSON.stringify(postData)) //3、发送请求(需发送字符串,将json转化成字符串)

(3)用Promise优化

function ajax(url) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest() //1、创建连接
        xhr.open('GET', url, true) //2、连接服务器
        xhr.onreadystatechange = function () { //4、接收请求,当状态改变时触发这个函数
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {//xhr.responseText是字符串需转换为JSON
                    resolve(JSON.parse(xhr.responseText))
                }else if(xhr.status === 404){
                    reject(new Error('404'))
                }
            }
        }
        xhr.send(null) //3、发送请求
    })
} 
const url = ''
ajax(url)
.then(res => console.log(JSON.parse(xhr.responseText)))
.catch(err => console.log(err))
上一篇 下一篇

猜你喜欢

热点阅读