this指向问题
一般情况下,this指向调用该函数的对象
- 全局作用域和普通函数中的this指向全局对象window*
console.log(this) //指向window
function fn(){
console.log(this) //也指向window
}
- 方法调用中谁调用就指向谁
let o ={
sayHi:function(){
console.log(this)
}
}
o.sayHi() //这里的this就指向o这个对象
- 构造函数中this指向构造函数实例
function Fun(){
console.log(this)
}
let fun = new Fun(); //this指向fun这个实例
几个需要注意的例子
- 箭头函数没有自己的this,会指向包含他的this
- setTimeout / setInterval 里的this指向window