(一)this指向
1.全局this ==> window
2.函数的this ==> 谁调用指向谁
3.对象方法上的this ==> 谁调用指向谁
4.事件响应函数中的this ==> 事件源
5.定时器中的this ==> window
6.箭头函数的this ==> 上一级作用域
(二)改变this指向的方法
1.call()
借出去的对象.方法.call(借给谁,参数1,参数2,参数3)
2.apply()
借出去的对象.方法.apply(借给谁,[参数1,参数2,参数3])
call()与apply()都是“立即执行”
eg:
const user1 = {
name: '小白',
food: '年糕',
say(food1, food2) {
console.log(this.name + '爱吃' + this.food + '和' + food1 + ',' + food2)
}
}
const user2 = {
name: '小黑',
food: '芝麻糊',
}
user1.say.call(user2, '西瓜', '葡萄') // 小黑爱吃芝麻糊和西瓜,葡萄
user1.say.apply(user2, ['土豆', '雪糕']) // 小黑爱吃芝麻糊和土豆,雪糕
3.bind()
一般用在回调函数中,永久的改变this指向
eg:
const user = {
name: '小白',
sayName() {
setTimeout(function(){
console.log(this) // window
}, 1000)
}
}
user.sayName()
改变this指向:
const user = {
name: '小白',
sayName() {
setTimeout(function(){
console.log(this) // user
}.bind(this), 1000)
}
}
user.sayName()