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
严格模式下的区别
- 严格模式下全局作用域里的函数里的this 指向 undefined
- 严格模式下 构造函数不加new 调用,this指向是undefined 会报错
- 定时器的this还是指向 window
- 事件和对象还是指向调用者