js call()、apply()、bind()

call()、apply()、bind()

相同点:都是改变this的指向

区别一 如下所示   bind 返回的是一个新的函数,必须调用它才会被执行

var name = 'lily', age = 11
    var person = {
      name: '剑姬',
      oAge: this.age,
      full: function() {
        return this.name + " " + this.age;
      }
    }
    var abc = {
      name: "郭磊",
      age: 16
    }
  

person.full() // 剑姬 undefined
person.full.call(abc) // 郭磊 16
person.full.apply(abc) // 郭磊 16
person.full.bind(abc)() // 郭磊 16

区别二 如下:call() 的第二个参数是字符串 

             apply() 的所有参数必须放在数组里

           bind() 除了返回函数以外,其他的跟call()一样

var name = 'lily', age = 11
    var person = {
      name: '剑姬',
      oAge: this.age,
      full: function(from, to) {
        return `${this.name} ${this.age} ${from} ${to}`;
      }
    }
    var abc = {
      name: "郭磊",
      age: 16
    }

    console.log(person.full.call(abc, '北京', '山东'))  //郭磊 16 北京 山东
    console.log(person.full.apply(abc, ['北京', '山东']))  //郭磊 16 北京 山东
   console.log(person.full.bind(abc, '北京', '山东')) //函数体
    console.log(person.full.bind(abc, ['北京', '山东'])())  //郭磊 16 北京,山东 undefined

  

原文地址:https://www.cnblogs.com/guoxianglei/p/13646675.html