1. 全局作用域或普通函数中
this
指向全局对象window
2. 方法(对象所有函数)
谁调用,this
就指向谁。
3. 构造函数
this
指向构造函数的实例对象
4. 箭头函数
当声明一个普通函数时,会定义一个this
对象,指向当前函数所属运行环境。
箭头函数没有this
,所以在箭头函数中使用this
时,会向外找,直到找到为止。
仅个人理解,有误的地方还请大家指出。
示例一:
var o = {
say(){
console.log(this);
},
eat: () => {
console.log(this);
}
}
o.eat(); // window
说明:
eat()
向外找,最终找到了对象o
外面的this
,即window
示例二:
var o = {
say(){
console.log(this);
},
eat(){
setTimeout(() => {
console.log(this);
})
}
}
o.eat(); // o
说明:
setTimeout
中的箭头函数向外找到setTimeout
外面的this
,即o