this指针(一般情况):
this 的指向在函数定义时是确定不了的,只有函数执行时才能确定 this 到底指向谁,一般情况下,this 的最终指向是调用自己的对象。
1.全局作用域或普通函数中的 this 指向全局对象 window
注意:定时器中的 this 指向 window,因为定时器是 window 调用的
2.方法调用中谁调用 this 就指向谁
3.构造函数中 this 指向构造函数的实例对象
4.Vue中 this 指向 Vue实例对象
箭头函数中的this指针:
1.this 是静态的,this 始终指向函数声明时所在作用域下的 this 的值
(简单来说,箭头函数没有自己的 this ,所以它去找自己作用域链的上一层的 this)
2.基于箭头函数的 this 是静态的,故 箭头函数适用于和 this 无关的回调
(类似于:定时器,数组的方法回调)
可以从如下案例中了解 this 的指向问题:
//普通方法:
let div = document.querySelector('div');
div.addEventListener('click', function() {
let _this = this; //先将指向函数调用者 div 的 this 存储下来
setTimeout(function() {
//修改背景颜色 使用this
_this.style.backgroundColor = 'pink'; //_this指向的才是 div 若采用 this 则指向的是 window(因为定时器的this是window)
},2000);
});
//箭头函数:
let div = document.querySelector('div');
div.addEventListener('click', function() {
// let _this = this;
setTimeout(() => { //箭头函数可以省略function
//修改背景颜色 使用this
this.style.backgroundColor = 'pink'; //箭头函数的this始终指向函数声明时所在作用域下的 this 的值(自己作用域链的上一层的 this 即为 div)
},2000);
});