js---ES6 箭头函数的this指向

普通函数的this指向看的是:

1.调用者

2.有没有call/apply改变this指向

3.new改变AO中的this为一个空的对象

4.什么都没有,单纯调用函数,this就是window,在自己的AO中。

箭头函数的this指向:箭头函数在定义时执行器上下文的this的指向(不具有块级作用域),即会取当前的函数的作用域链上的this,忽略块级作用域中的this

  function haha(){
            let Person = {
            'name1': 'little bear',
            'age': 18,
            'sayHello': function () {
                console.log(this);//Person,以下为Person.sayHello的结果
                var self = this;
                setTimeout(()=>{
                    console.log('我叫' + self.name1 + '我今年' + self.age + '岁!')
                }, 1000); //我叫little bear我今年18岁!
                setTimeout(()=>{
                    console.log('我叫' + this.name1 + '我今年' + this.age + '岁!')
                }, 1000);//我叫little bear我今年18岁!
                setTimeout(function(){
                    console.log('我叫' + this.name1 + '我今年' + this.age + '岁!')
                }, 1000);//我叫undefined我今年undefined岁!
                setTimeout(function(){
                    console.log('我叫' + self.name1 + '我今年' + self.age + '岁!')
                }, 1000);//我叫little bear我今年18岁!
            },
            say:()=>{
                console.log(this);//haha函数构造的空对象,如果不用haha函数包起来,那么这个this是window
            }
        }
        // Person.sayHello();//this是Person
        //var sayHelloFun = Person.sayHello
        // sayHelloFun();//this是window
        Person.say();
        // var say=Person.say;
        // say();
        // localStorage.name1="anhe";
        // sessionStorage.age=17;
            function ceshi(){
                console.log(this);//ceshi构造的空对象
                Person.say();//内部this是haha构造出来的对象,证明和调用位置无关,与定义位置的上下文中的this有关
            }
            new ceshi();
        }
       let xi= new haha();


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值