ES6指针函数this指向
=>this指向的是定义时this指向的对象,不会改变
function()声明函数时的this指向会指向使用时所在的对象
箭头函数和普通函数的区别
-
普通函数:根据调用我的人(谁调用我,我的this就指向谁)
-
箭头函数:根据所在的环境(我在哪个环境中,this就指向谁)
一个简单的例子
//1
document.onclick = function () {
alert(this); //HTMLDocument
}
document.onclick = () => {
alert(this); //Window
}
//2
document.onclick = function () {
let arr = [1, 2, 3];
arr.a = function () {
alert(this);
}
arr.a(); //1,2,3
}
document.onclick = function () {
let arr = [1, 2, 3];
arr.a = () => {
alert(this);
}
arr.a(); //HTMLDocument
}
//3
function timer(){
this.age = 18;
var _this = this;
setTimeout(function(){
console.log(this);//指向了全局window
console.log(this.age);//undefined
console.log(_this.age);//18
},1000);
setTimeout(()=>console.log(this.age),1500);//18
};
var timer2 = new timer();
我用防抖和节流的代码又对箭头函数的this指向进行了验证。(看防抖和节流文章,将普通函数和指针函数相互换一下然后输出this和arguments进行查看)