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

手写apply、call、bind

作者头像
用户3258338
发布2020-02-17 14:34:50
4020
发布2020-02-17 14:34:50
举报

你还是我的快乐,好在不会勾起我的忧伤了~

各位宝宝,马上就要过中国年了,已经开启了放假模式了吗?放假了就好好的休息哈,该玩的时候玩、该学的时候学,就对了~

手写call

代码语言:javascript
复制
Function.prototype.myCall = function(context){
  if(typeof this != 'function'){
    throw New TypeError('Error')
  }
  let context = context || window
  let args = [...arguments].slice(1)
  context.fn = this;
  let result = context.fn(...args)
  delete context.fn;
  return result;
}

手写apply

代码语言:javascript
复制
Function.prototype.myCall = function(context){
  if(typeof this !=== 'function'){
    throw new TypeError('Error')
  }
  context = context || window;
  context.fn = this;
  let result;
  if(arguments[1]){
    result = context.fn(...arguments[1])
  }else{
    result = context.fn()
  }
  delete context.fn
  return result
}

手写bind

代码语言:javascript
复制
Function.prototype.myBind = function(context){
  if(typeof this !== 'function'){
    throw new Typeerror('Error')
  }
  const _this = this;
  const args = [...arguments].slice(1)
  // bind的返回值是一个函数
  return function F(){
     // 函数有两种调用方式,一种是new ,一种是直接调用
    if(this instanceof F){
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }  
}

愿我们有能力不向生活缴械投降---Lin

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 女程序员的日常 微信公众号,前往查看

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

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

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