Skip to content

高频

实现防抖函数

js
// fn是用户传入需要防抖的函数
// delay是等待时间
const debounce = (fn,delay = 50) => {
  // 缓存一个定时器id
  let timer = null
  // 这里返回的函数是每次用户实际调用的防抖函数
  // 如果已经设定过定时器了就清空上一次的定时器
  // 开始一个新的定时器,延迟执行用户传入的方法
  return funtion (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(()=>{
      fn.apply(this.args)
    }, delay)
  }
}

实现节流函数

js
// 时间戳
// fn是用户传入需要防抖的函数
// delay是等待时间
const throttle = (fn,delay = 50) => {
  // 记录上一次的时间
  let lastTime = 0
  return funtion (...args) {
    // 记录当前函数触发的时间
    let now = +new Date()
    // 判断上次触发的时间和本次触发的时间差是否大于时间间隔的阈值
    // 如果大于,则执行函数
    if (now - lastTime > delay) {
      fn.apply(this,args)
      lastTime = now
    }
  }
}

// 定时器
// fn是用户传入需要防抖的函数
// delay是等待时间
const throttle = (fn,delay = 50) => {
  // 记录上一次的时间
  let timer = null
  // args是用户传入的参数
  return funtion (...args) {
    // 判断上一次的定时器是否存在
    // 如果不存在,则开始一个定时器,延迟执行用户传入的方法
    if (!timer) {
      timer = setTimeout(()=>{
        fn.apply(this,args)
        timer = null
      }, delay)
    }
  }
}

getType函数

js
const getType = (obj) => {
  let originType = Object.prototype.toString.call(obj)
  let index = originType.indexOf(' ')
  let type = originType.slice(index + 1, -1)
  return type.toLowerCase()
}

实现instanceOf

js
// 实例.__ptoto__ === 构造函数.prototype
const myInstanceof = (instance, classOrFunc) => {
  // 由于instance要检测的是某对象,需要有一个前置判断条件
  //基本数据类型直接返回false
  if (typeof instance !== 'object' || instance === null) return false
  // 等价于 instance.__ptoto__
  let proto = Object.getPrototypeOf(instance)
  while (proto) {
    // 当proto == null时,说明已经找到了Object的基类null 退出循环
    // // 实例的原型等于当前构造函数的原型,返回true
    if (proto === classOrFunc.prototype) return true
    // 继续沿着原型链向上查找,沿着原型链__ptoto__一层一层向上查
    // 等价于 proto.__ptoto__
    proto = Object.getPrototypeOf(proto)
  }
  return false
}

实现new的过程

js
const myNew = (func, ...args) => {
  // 1.创建一个空对象
  let obj = {}
  // 2.设置原型,将对象的原型设置为函数的 prototype 对象。
  Object.setPrototypeOf(obj, func.prototype)
  // 3.让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
  let result = func.apply(obj, args)
  // 4.判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。
  return result instanceof Object ? result : obj
}

实现call方法

js
Function.prototype.myCall = function (context, ...args) {
  if (!context || context === null) {
    context = window
  }
  // 创建一个唯一的Symbol属性的key值,作为context的属性名
  let fn = Symbol()

  //
  context[fn] = this

  return context[fn](...args)
}

实现apply方法

js
Function.prototype.myApply = function (context, args) {
  if (!context || context === null) {
    context = window
  }
  let fn = Symbol()
  context[fn] = this
  return context[fn](...args)
}

实现bind方法

js
Function.prototype.myBind = function (context, ...args) {
  const fn = this
  args = args || []
  return function newFn(...newFnArgs) {
    if (this instanceof newFn) {
      return new fn(...args, ...newFnArgs)
    }
    return fn.apply(context, [...args, ...newFnArgs])
  }
}

实现深拷贝

js
const deepClone(obj) => {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }
  let copy = {}

  if (obj.constructor === Array) {
    copy = []
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = deepClone(obj[key])
    }
  }

  return copy
}

实现类的继承

js
class People {
  constructor(name = 'water', age = '27') {
    this.name = name
    this.age = age
  }
  eat() {
    console.log(`${this.name} ${this.age} eat food`)
  }
}

class Woman extends People {
  constructor(name = 'ren', age = '27') {
    super(name, age)
  }
  eat() {
    super.eat()
  }
}

实现ajax请求

js
const ajax = (url) => {
  let xhr = new XMLHttpRequest() //实例化,以调用方法
  xhr.open('get', url) //参数2,url。参数三:异步
  xhr.onreadystatechange = () => {
    //每当 readyState 属性改变时,就会调用该函数。
    if (xhr.readyState === 4) {
      //XMLHttpRequest 代理当前所处状态。
      if (xhr.status >= 200 && xhr.status < 300) {
        //200-300请求成功
        let string = request.responseText
        //JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象
        let object = JSON.parse(string)
      }
    }
  }
  request.send() //用于实际发出 HTTP 请求。不带参数为GET请求
}

// promise实现
const ajax = (url) => {
  const p = new Promise(() => {
    let xhr = new XMLHttpRequest()
    xhr.open('get', url)
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status <= 300) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          reject('请求出错')
        }
      }
    }
    xhr.send()
  })
  return p
}

实现jsonp请求

js
const jsonp = (url,jsonpCallback,success) {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.type = 'text/javascript'
  window[jsonpCallback] = function(data) {
    success && success(data)
  }
    document.body.appendChild(script)
}

实现一个compose函数

js
const compose = (...fn) {
  if (!fn.length) return v => v
  if(fn.length === 1) return fn[0]
  return fn.reduce((pre,cur)=>{
    return (...args) => pre(cur(...args))
  })
}

seTimeout实现setInterval

js
const mySetTimeout = (fn, time) => {
  const timer = setInterval(() => {
    clearInterval(timer)
    fn()
  }, time)
}

mySetTimeout(() => {
  console.log(1)
}, 1000)

setInterval实现setTimeout

js
const mySetInterval = (fn, time) => {
  let timer = null
  function interval() {
    fn()
    timer = setTimeout(interval, time)
  }
  interval()
  return {
    cancel: () => {
      clearTimeout(timer)
    },
  }
}

最后更新于:

如有转载或 CV 的请标注本站原文地址