箭头函数的this 指向

复制代码
复制代码
let p ={
    num:1,
    add: function(a){
        
        let f = v => {
            //箭头函数没有this,往上找一层的this 就是箭头函数的this
            // 箭头函数没有this  不能用call  apply bind 进行绑定
            console.log(this)
            return v + this.num
        
        }
        let b = {num:3}
        return f.call(b, a)
    }
}
console.log(p.add());


/***
 *普通函数可以用bind,call apply 改变箭头函数的指向,
 *箭头函数没有this ,不可以通过bind 、call、apply改变this 指向的
 **/
let p ={
    num:1,
    current: this// 对象里面的this.一般指向Window、主要看调用者是谁,call apply bind 会改变this 指向
    add:(a)=>{
        ()=>{
      //当前的this 指向的是上一层函数的this,上一层如果还是箭头函数没有this,继续往上找,p 对象里面的current ,window对象,就是此时的this
      console.log(this.name)
     }
    }
}
console.log(p.add());  //输出为空因为 window是name 属性没有值
复制代码

 

复制代码

posted on   totau  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示