apply call bind

2021-10-31  本文已影响0人  hszz
  1. 都能修改函数的this指向
  2. 第一个参数都是this的指向对象,并且可以继续传参(参数形式有所不同)
  3. apply call是立即执行, 而bind是返回一个函数,可以稍后执行

写法

简单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
上一篇 下一篇

猜你喜欢

热点阅读