下面5种情况均在不使用箭头函数的前提下,箭头函数中this指向它被定义时环境的this
1.普通函数中this指向window
function a(){
console.log(this);
}
a() // window对象
2.对象的方法中this指向该对象
let color = 'green'
let test = {
color: 'blue',
getColor: function(){
let color = "red";
console.log(this.color); // this指向test对象,输出blue
console.log(color) // 就近原则,在green和red中选择,输出red
}
}
-------------------------------分割线-------------------------------------
let color = 'green'
let test = {
color: 'blue',
getColor: function(){
console.log(color);
}
}
test.getColor() // 输出green
3.构造函数中this指向实例化对象
function Person(name, age){
this.name = name
this.age = age
}
let zb = new Person('zb', 'red')
console.log(zb.name);
4.事件绑定的方法中this指向绑定事件对象
let img = document.querySelector('div')
img.addEventListener('click',function(){
console.log(this); // this指向绑定click事件的DOM对象img
})
5.定时器函数,循环执行函数,立即执行函数this指向Window
定时器函数
let a = setTimeout(function () {
console.log(this) // 输出Window对象
}, 2000)
------------------------------分割线-------------------------
循环执行函数
let a = setInterval(()=>{
console.log(this) // 输出Window对象
}, 2000)
------------------------------分割线-------------------------
立即执行函数
(function(){
console.log(this) // 输出Window对象
})()