以下javascript代码编写在index.html的script标签中:
普通函数:
let a = {
af:function(){
console.log(this)
},
b:{
bf:function() {
console.log(this)
},
c:{
cf:function(){
console.log(this);
}
}
}
}
a.af()//输出a对象
a.b.bf()//输出b对象
a.b.c.cf()//输出c对象
发现普通函数的this指向其直接所属的对象。
箭头函数:
let b = {
af:()=>{
console.log(this)
},
b:{
bf:()=>{
console.log(this)
},
c:{
cf:()=>{
console.log(this);
}
}
}
}
b.af()//全部输出全局的window对象
b.b.bf()//
b.b.c.cf()//
箭头函数没有自己的this指向,因此它需要继承 父级函数 的this ,因此this指向window。我的理解是箭头函数一直往外面找,如果找到了 父级普通函数,那么this就指向 该普通函数所属的对象。在上述例子中,箭头函数一直在往上找父级别普通函数,最终以window作为this指向。
下述例子更能证明上述结论:
let c ={
f:function(){
let innerF = ()=> {
console.log("非箭头函数,内嵌1个箭头函数");
console.log(this);
let innerF2 = ()=> {
console.log("非箭头函数,内嵌2个箭头函数");
console.log(this);
}
innerF2()
}
innerF()
},
}
c.f()
输出结果:
内嵌的函数往作用域上找,找到了f这个普通函数,于是把this指向f所属对象c。