前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaScript深入之手写call、apply、bind

JavaScript深入之手写call、apply、bind

作者头像
peng_tianyu
发布2022-12-15 18:00:26
2230
发布2022-12-15 18:00:26
举报
文章被收录于专栏:前端开发随记

模拟实现call

  • 将函数设为对象的属性
  • 执行该函数
  • 删除该函数
代码语言:javascript
复制
Function.prototype.myCall = function(context = window, ...args) {
  if(this === Function.prototype) {
    return undefined 
  }
  context = context || window
  const fn = Symbol()
  context[fn] = this
  const result = context[fn](...args)
  delete context[fn]
  return result
}

模拟实现apply

  • 与call方法类似,参数为数组
代码语言:javascript
复制
Function.prototype.myApply = function(context = window, args) {
  if(this === Function.prototype) {
    return undefined
  }
  const fn = Symbol()
  context[fn] = this
  let result
  if(Array.isArray(args)) {
    result = context[fn](args) 
  } else {
    result = context[fn] 
  }
  delete context[fn]
  return result
}

模拟实现bind

  • 返回一个新函数
  • 新函数this指向bind的第一个参数
  • 其余参数作为新函数的参数传入
代码语言:javascript
复制
Function.prototype.myBind = function(context = window, ...args1) {
  if(this === Function.prototype) {
    throw new TypeError('Error') 
  }
  const _this = this
  return function F(...args2) {
    if(this instanceof F) {
      return new _this(...args1, ...args2) 
    }
    return _this.apply(context, args1.concat(args2))
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-04-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模拟实现call
  • 模拟实现apply
  • 模拟实现bind
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档