bind,call和apply的区别及实现方式

  1. 都是改变this指向
  2. 三者第一个参数都是this要指向的对象,如果没有第一个参数或者参数为null或undefined,则默认指向window
  3. 都可以传参:call可以传入多个字符串,apply是一个数组,call和apply都是一次传入,而bind可以多次传入
  4. bind是返回绑定之后的函数,而call和apply是绑定即执行
Function .prototype.myCall = function (ctx = window, ...args) {
    ctx.fn = this
    const result = ctx.fn(...args)
    delete ctx.fn
    return result
}

// 使用demo
const obj1 = {
    num: 1,
    sum(a, b) {
      console.log(this)
      return this.num + a + b
    } 
}
const obj2 = {
    num: 10
}
console.log(obj1.sum.call(obj2, 2, 3)) // 15
console.log(obj1.sum.myCall(obj2, 2, 3)) //15
Function.prototype.myApply = function (ctx = window, args) {
  ctx.fn = this
  const result = ctx.fn(...(args || []))
  delete ctx.fn
  return result
}

// 使用demo
console.log(obj1.sum.myApply(obj2, [2, 3])) // 15
Function.prototype.myBind = function (ctx = window, ...initargs) {
  return (...args) => {
    ctx.fn = this
    const result = ctx.fn(... args,...initargs)
    delete ctx.fn
    return result
  }
}
// demo
console.log(obj1.sum.myBind(obj2, 2)(3)) // 15
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容