六个初级前端要掌握的手写

前言

回调函数为什么会丢失this,因为回调时的传参某种程度上也是一种隐式赋值,因此会造成隐式丢失的情况。

防抖

const debouce = (fn, delay) => {
  let timer = null
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

节流

const throttle = (fn, delay) => {
  let flag = true
  return (...args) => {
    if(!flag) return
    flag=false
    setTimeout(() => {
      fn.apply(this, args)
      flag=true
    }, delay)
  }
}

new

function create(func, ...args) {
  let obj = {}
  Object.setPrototypeOf(obj, func.prototype)
  let result = func.apply(obj, args)
  return result instanceof Object?result:obj
}

call

function A(){console.log(this.name)}
A.mycall({name:1})

Function.prototype.mycall = function (c, ...args) {
  let c = c||window
  c.fn = this
  let res = eval('c.fn(...args)')
  delete c.fn
  return res
}

apply

Function.prototype.myapply = function(a, args) {
  let a = a||window
  a.fn = this
  let res = eval('a.fn(...args)')
  delete a.fn
  return res
}

bind

Function.prototype.mybind = function(b, ...args) {
  if(typeof this!=='function') {
    throw new Error('需要函数')
  }
  let self = this, fNOP = function(){}
  let fbound = function(){
    self.apply(this instance of self ? this : context, args.concat(Array.prototype.slice.call(arguments)))
  }
  fNOP.prototype = this.prototype
  fbound.prototype = new fNOP()
  return fbound
}
发布了371 篇原创文章 · 获赞 391 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43870742/article/details/104289576
今日推荐