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();


猜你喜欢

转载自blog.csdn.net/github_39132847/article/details/80164815