美文网首页
JS常见手写代码题(二)

JS常见手写代码题(二)

作者: kugua666 | 来源:发表于2020-08-21 13:36 被阅读0次

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))

相关文章

  • JS常见手写代码题(二)

    1、用闭包手写一个cache工具 2、手写一个简易的JQuery,考虑插件和扩展性 3、手写Promise加载一张...

  • JS常见手写代码题(一)

    1、call bind applycall 、bind 、apply三个都是用来改变函数的this对象的指向,第一...

  • 手写代码题

    深浅拷贝 深拷贝和浅拷贝值针对 Object 和 Array 这样的复杂类型 浅拷贝 只复制对象第一层属性,如果基...

  • js手写题

    写在最前:文章转自掘金[https://juejin.cn/post/6946022649768181774] 时...

  • 搜狗面试

    原型链上手写事件,手写原生js实现ajax事件,jsonp实现原理,阻止事件IE冒泡代码,事件捕获、处理,冒泡代码...

  • 前端常见手写代码

    1.call()函数的实现步骤 判断调用对象是否为函数,即使是定义在函数的原型上的,但是可能出现使用 call 等...

  • js常见题

    https://www.cnblogs.com/cutenana/p/7398255.html

  • js常见题

    1.require 与 import 的区别 两者的加载方式不同、规范不同 第一、两者的加载方式不同, requi...

  • Java多线程---顺序打印ABC打印10次的实现-三种实现

    这是一道常见的面试题,如果遇到需要手写代码这种题,首先是要理清思路,再就是尽量体现出代码风格,关键次是顺序,一、基...

  • 错一步便是云泥之别,五面字节Java岗,从小公司到字节的面经总结

    1.面试 笔试常见的问题面试常见的问题下面给的面试题基本都有。1 手写代码:手写代码一般会考单例、排序、线程、消费...

网友评论

      本文标题:JS常见手写代码题(二)

      本文链接:https://www.haomeiwen.com/subject/alyujktx.html