美文网首页
一些手写js

一些手写js

作者: loloht | 来源:发表于2020-08-24 17:02 被阅读0次

    实现new方法

    实现new方法步骤

    1. 创建一个新对象
    2. 绑定原型
    3. 绑定this对象
    4. 返回新对象
    function _new() {
     // 缓存一个arguments,避免直接修改污染arguments
     let _arguments = arguments;
      // 拿到构造函数,shift处理之后_arguments值已经更改,shift会对原始数据有影响
     let fn = Array.prototype.shift.call(_arguments)            
      // 第一步,创建一个对象
     let target = {};
      // 第二步,链接到原型,给新对象的隐式原型赋予构造函数的显示原型,得到构造函数的所有prototype属性值            
     target.__proto__ = fn.prototype;
      // 第三步,把当前的this指针指向新的对象
     fn.apply(target, _arguments);
      // 第四步,返回当前this   
     return target;
    }
    

    手写bind

    Function.prototype.my_bind = function (context) {
        let args = Array.prototype.slice.call(arguments, 1);
        var self = this;
        return function () {
            var ht = Array.prototype.slice.call(arguments);
            var kt = args.concat(ht);
            return selt.apply(context, kt);
        }
    }
    

    深拷贝浅拷贝

    浅拷贝

    // 1. ...实现
    let copy1 = {...{x:1}}
    
    // 2. Object.assign实现
    let copy2 = Object.assign({}, {x:1})
    

    深拷贝

    // 1. JOSN.stringify()/JSON.parse()  
    // 缺点:拷贝对象包含 正则表达式,函数,或者undefined等值会失败
    let obj = {a: 1, b: {x: 3}}
    JSON.parse(JSON.stringify(obj))
    
    // 2. 递归拷贝
    function deepClone(obj) {
      let copy = obj instanceof Array ? [] : {}
      for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
          copy[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
        }
      }
      return copy
    }
    

    节流函数

    在规定时间内只触发一次

    function fn() {
        console.log('节流')
    }
    addEventListener('scroll', throttle(fn, 1000))
    
    function throttle(fn, wait) {
        var prev = 0;
        return function () {
            var nowtime = new Date();
            if (nowtime - prev >= wait) {
                fn.apply(this, arguments);
                prev = nowtime;
            }
        }
    }
    

    防抖函数

    在规定时间内未触发第二次,则触发

    function fn() {
        console.log('防抖')
    }
    addEventListener('scroll', debounce(fn, 1000))
    
    function debounce(fn, wait) {
        var timer = null;
        return function () {
            var args = arguments;
            timer && clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(this, args )
            }, wait);
        }
    }
    

    Object.create 的基本实现原理

    将传入的对象作为原型

    function newCreate (obj) {
        function F(params) {
            
        }
        F.prototype = obj;
        return new F()
    }
    

    手写ajax

    // 1. 简单流程
    
    // 实例化
    let xhr = new XMLHttpRequest()
    // 初始化
    xhr.open(method, url, async)
    // 发送请求
    xhr.send(data)
    // 设置状态变化回调处理请求结果
    xhr.onreadystatechange = () => {
      if (xhr.readyStatus === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
    
    // 2. 基于promise实现
    
    function ajax (options) {
      // 请求地址
      const url = options.url
      // 请求方法
      const method = options.method.toLocaleLowerCase() || 'get'
      // 默认为异步true
      const async = options.async
      // 请求参数
      const data = options.data
      // 实例化
      const xhr = new XMLHttpRequest()
      // 请求超时
      if (options.timeout && options.timeout > 0) {
        xhr.timeout = options.timeout
      }
      // 返回一个Promise实例
      return new Promise ((resolve, reject) => {
        xhr.ontimeout = () => reject && reject('请求超时')
        // 监听状态变化回调
        xhr.onreadystatechange = () => {
          if (xhr.readyState == 4) {
            // 200-300 之间表示请求成功,304资源未变,取缓存
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
              resolve && resolve(xhr.responseText)
            } else {
              reject && reject()
            }
          }
        }
        // 错误回调
        xhr.onerror = err => reject && reject(err)
        let paramArr = []
        let encodeData
        // 处理请求参数
        if (data instanceof Object) {
          for (let key in data) {
            // 参数拼接需要通过 encodeURIComponent 进行编码
            paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
          }
          encodeData = paramArr.join('&')
        }
        // get请求拼接参数
        if (method === 'get') {
          // 检测url中是否已存在 ? 及其位置
          const index = url.indexOf('?')
          if (index === -1) url += '?'
          else if (index !== url.length -1) url += '&'
          // 拼接url
          url += encodeData
        }
        // 初始化
        xhr.open(method, url, async)
        // 发送请求
        if (method === 'get') xhr.send(null)
        else {
          // post 方式需要设置请求头
          xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
          xhr.send(encodeData)
        }
      })
    }
    

    rem 基本设置

    // 提前执行,初始化 resize 事件不会执行
    setRem()
    // 原始配置
    function setRem () {
      let doc = document.documentElement
      let width = doc.getBoundingClientRect().width
      let rem = width / 75
      doc.style.fontSize = rem + 'px'
    }
    // 监听窗口变化
    addEventListener("resize", setRem)
    

    实现懒加载

    <ul>
      <li><img src="./imgs/default.png" data="./imgs/1.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/2.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/3.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/4.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/5.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/6.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/7.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/8.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/9.png" alt=""></li>
      <li><img src="./imgs/default.png" data="./imgs/10.png" alt=""></li>
    </ul>
    let imgs =  document.querySelectorAll('img')
    // 可视区高度
    let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    function lazyLoad () {
      // 滚动卷去的高度
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      for (let i = 0; i < imgs.length; i ++) {
        // 图片在可视区冒出的高度
        let x = clientHeight + scrollTop - imgs[i].offsetTop
        // 图片在可视区内
        if (x > 0 && x < clientHeight+imgs[i].height) {
          imgs[i].src = imgs[i].getAttribute('data')
        }
      }
    }
    // addEventListener('scroll', lazyLoad) or setInterval(lazyLoad, 1000)
    

    实现一个双向绑定

    let obj = {}
    let input = document.getElementById('input')
    let span = document.getElementById('span')
    // 数据劫持
    Object.defineProperty(obj, 'text', {
      configurable: true,
      enumerable: true,
      get() {
        console.log('获取数据了')
      },
      set(newVal) {
        console.log('数据更新了')
        input.value = newVal
        span.innerHTML = newVal
      }
    })
    // 输入监听
    input.addEventListener('keyup', function(e) {
      obj.text = e.target.value
    })
    

    相关文章

      网友评论

          本文标题:一些手写js

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