bind、apply、call的区别

103 阅读1分钟

相同点:

  • 都能改变this指向
  • 第一个参数都是this
  • 都可以进行后续传参
  • 都是来源于Function.prototype,属于实例方法
  •   console.log(Function.prototype.hasOwnProperty('call')) //true
      console.log(Function.prototype.hasOwnProperty('apply')) //true
      console.log(Function.prototype.hasOwnProperty('bind')) //true
    

不同点:

  • call和bind的可接收任意参数
  • apply只有两个参数,第二个参数是个数组
  • call和apply是立即执行,而bind方法不是立即执行的,它返回包含this指向的函数,还需要调用一下
  •   //接收参数
      
      function func (a,b,c) {
          console.log(a, b, c)
      }
      
      func.call(null, 1,2,3) //func 接收到的参数实际上是 1,2,3
      func.call(undefined, [1,2,3]) //func 接收到的参数实际上是 [1,2,3],undefined,undefined
      
      func.apply(null, [1,2,3])//数组  func接收到的参数实际上是 1,2,3
      func.apply(undefined, { 0: 1, 1: 2, 2: 3,length: 3}) // 类数组 func收到的也是 1,2,3
      
      func.bind(null, 1,2,3)() //func 接收到的参数实际上是 1,2,3
      func.bind(null)([1,2,3]) //func 接收到的参数实际上是 [1,2,3],undefined,undefined
      
      
      
      //改变this指向
      
      let personA = {
        name: '李世民',
        sex: '男',
        say: function(x){
          console.log(this.name+ '是'+ x)
        }
      }
      
      personA.say.bind({name: '秦始皇'})('男的') //秦始皇是男的
      personA.say.apply({name: '花木兰'}, ['女的']) //花木兰是女的
      personA.say.call({name: '英语老师'}, '是教书的') //英语老师是教书的
    

​apply的妙用

let max = Math.max.apply(null, array); //求数组最大值