【JavaScript】绑定 this 之 apply call bind

绑定 this

var o1 = {
  name: 'o1',
  f1: function() {
    console.log(this.name)
  }
}

var o2 = {
  name: 'o2',
  f2: function() {
    console.log(this.name)
  }
}

o1.f1.call(o2) //o2

apply

var args = [1, 2, 3]
console.log.apply(console, args)
// apply 会把 args 拆成一个个的参数传给函数
// 相当于 
console.log(1, 2, 3)

call

console.log.call(console, 1, 2, 3)
// call 只能把参数一个个传入
// 相当于 
console.log(1, 2, 3)

bind

var log = console.log.bind(console, '这里是额外参数')
log('hello') // 这里是额外参数 hello

你可能感兴趣的:(javascript)