call apply bind

254 阅读1分钟

call apply bind 的区别

  1. call(obj)/apply(obj):调用函数,指定函数中this为第一个参数的值
  2. bind(obj):返回一个新的函数,新函数内部会调用原来的函数,this为bind指定的第一个参数
  • 如果obj是null/undefined,this为window
  function fn(a, b) {
    this.xxx = 3
    console.log(a, b, this)
  }
  fn(1, 2)
  console.log(xxx)
  const obj = {
    m: 0
  }
  fn.call(obj, 1, 2)
  fn.apply(obj, [1, 2])
  fn.call(undefined, 1, 2)
  fn.call(null, 1, 2)
  fn.bind(obj,1,2)(4,5) 

应用

  1. 把维数组转换为真正的数组

手写call apply bind

  1. 手写 call
  Function.prototype.call = function (obj, ...args) {
    console.log('call')
    // this(...agrs)
    //处理obj为null或者undefined的情况
    if (obj === null || obj === undefined) {
      obj = window
    }
    //给obj添加一个方法
    obj.temFn = this
    //调用obj的方法
    const result = obj.temFn(...args)
    //删除obj上的方法
    delete obj.temFn
    return result
  }
  1. 手写apply 和apply几乎一样
  Function.prototype.apply = function (obj, args) {
    console.log('apply')
    // this(...args)
    if (obj === null || obj === undefined) {
      obj = window
    }
    obj.temFn = this
    const result = obj.temFn(...args)
    delete obj.temFn
    return result
  }
  1. 手写bind
  Function.prototype.bind = function (obj, ...args) {
    console.log('bind')
    return (...args2) => {
      //调用原来的函数,且指定this为obj,参数为args 和args2组成
      return this.call(obj, ...args, ...args2)
    }
  }