4. 手写函数

本文介绍了如何手写JavaScript的Function.prototype扩展,包括自定义的mycall方法、bind的实现、防抖(debounce)函数以及实例化检查(instanceof)的原理,强调了原型链在这些功能中的关键作用。
摘要由CSDN通过智能技术生成

手写 call

Function.prototype.mycall = function (ctx, ...args) {
  ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
  // ctx 一定是对象
  const fn = this // 待执行的函数
  const key = Symbol('temp')
  Object.defineProperty(ctx, key, {
    enumerable: false,
    value: fn,
  })
  const result = ctx[key](...args)
  delete ctx[key]
  return result
}

手写 bind

// 只生效一次
function bind(ctx){
  return function(){
    if(当前函数是使用 new 来调用的){
      new 调用原始函数
    }else{
      原始函数.call(ctx)
    }
  }
}
Function.prototype.myBind = function (ctx) {
  var args = Array.prototype.slice.call(arguments, 1)
  var fn = this
  return function A(...args) {
    var restArgs = Array.prototype.slice.call(arguments)
    var allArgs = args.concat(restArgs)
    // 使用 new 的方式调用的这个函数
    if (Object.getPrototypeOf(this) === A.prototype) {
      // return new fn(...allArgs)
      var obj = {}
      Object.setPrototypeOf(obj, fn.prototype)
      fn.apply(obj, allArgs)
      return obj
    } else {
      return fn.apply(ctx, allArgs)
    }
  }
}

防抖

function debounce(func, duration = 500) {
  let timerId
  return function (...args) {
    clearTimeout(timerId)
    timerId = setTimeout(() => {
      func.apply(this, args)
    }, duration)
  }
}

手写 instanceof

instanceof 作用:

判断一个实例是否是其父类或者祖先类型的实例。

instanceof 在查找的过程中会遍历左边变量的原型链,直到找到右边变量的 prototype查找失败,返回 false

核心要点:原型链的向上查找。

let myInstanceof = (target, origin) => {
  while (target) {
    if (target.__proto__ === origin.prototype) {
      return true
    }
    target = target.__proto__
  }
  return false
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值