前言
在使用函数时,我们通常会把
this
指向弄不清除,今天就一起来看看吧!
this
出现的情况
- 普通函数中的
this
指向。- 箭头函数中的
this
指向。class
声明的函数中this
的指向。- 通过
call(),apply(),bind()
改变后的this
指向- 在对象中调用函数时的
this
指向。
案例
//普通函数
function fn(){
console.log(this) //指向window
}
fn()
//class函数
class Prom {
constructor(name) {
this.name = name
}
say() {
console.log(this)// this指向实例本身
}
}
var zhang = new Prom('hui')
zhang.say()
//计时器中的函数为普通函数时的this
class Prom {
constructor(name) {
this.name = name
}
say() {
setTimeout(function(){
console.log(this)// this指向window
})
}
}
var zhang = new Prom('hui')
zhang.say()
//计时器中的函数为箭头函数时的this
class Prom {
constructor(name) {
this.name = name
}
say() {
setTimeout(()=>{
console.log(this) //this指向实例本身
})
}
}
var zhang = new Prom('hui')
zhang.say()
- 在普通函数中
this
指向window
,通过call()
,apply()
,bind()
可以修改this指向。- 在箭头函数中this指向父级的上下文,通过
call()
,apply()
,bind()
无法修改this指向。- 在
class
定义的函数中this
指向实例本身。- 在对象中调用函数时,谁调用
this
就指向谁。- 在计时器的回调函数中,当函数为普通函数时,
this
指向window
;当函数为箭头函数时,this
指向实例本身。
自由变量
在当前作用域中使用了变量,却未定义会向上级作用域查找,找到
window
还没有找到,则报错。