JavaScript:手动实现call、apply、bind

  • call

1.把this增加到context this指向调用的方法
2.第0个传入的是指向的对象,这里只需要调用方法传入的形参
3.把截取的参数传给执行回调函数
4.删除context上增加的fn方法

Function.prototype.myCall = function (context = window) {
  context.Fn = this 
  const args = [...arguments].splice(1) 
  const res = context.Fn(...args) 
  delete context.fn 
  return res
}
  • apply 跟call类似,前者传多个参数,后者传入数组
Function.prototype.myApply = function (context = window) {
  context.Fn = this
  const args = [...arguments[1]] //传入的数组拿出来
  const res = context.Fn(...args)
  delete context.fn
  return res
}
  • bind 返回一个函数

1.保存this指向的方法
2.把传入的参数截取出来
3.返回一个函数,在把call引入到里面,返回出来

Function.prototype.myBind = function (context = window) {
  const _this = this 
  const args = [...arguments].splice(1)
  return function (...args2) {
    //...[...args, ...args2] 可能存在多次调用,所以把两者传入的参数合二为一
    return _this.call(context, ...[...args, ...args2])
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容