美文网首页
apply call bind

apply call bind

作者: hszz | 来源:发表于2021-10-31 13:30 被阅读0次
  1. 都能修改函数的this指向
  2. 第一个参数都是this的指向对象,并且可以继续传参(参数形式有所不同)
  3. apply call是立即执行, 而bind是返回一个函数,可以稍后执行

写法

  • func.apply(thisArg, [argsArray])
  • function.call(thisArg, arg1, arg2, ...)
  • function.bind(thisArg[, arg1[, arg2[, ...]]])

简单demo

var person = {
  firstName: '1',
  lastName: '23',
  fullName: function(city, country) {
    return this.firstName + this.lastName + '----' + city + ':' + country
  }
}

var person1 = {
  firstName: 'h',
  lastName: 'szz',
}

console.log(person.fullName('abc', 'def'))
console.log()

// apply
console.log( person.fullName.apply(person1, ['apply', 'apply']) )
console.log()

// call
console.log( person.fullName.call(person1, 'call', 'call') )
console.log()

// bind 会返回一个函数,可决定何时调用
console.log( person.fullName.bind(person1, 'bind', 'bind') )
console.log( person.fullName.bind(person1, 'bind', 'bind')() )
image.png
  • 如图所示, applycallbind 都改变了person.fullName()this指向,指向了person1

相关文章

网友评论

      本文标题:apply call bind

      本文链接:https://www.haomeiwen.com/subject/abonaltx.html