This指向

1.概念

1.this指向函数的直接调用者而非间接调用者

2.如果有new关键字,this指向new出来的那个对象

3.在DOM事件中,this指向目标元素

4.箭头函数的this指向他所在的函数级作用域,并且不可改变

2.案例

1.此时function()中传入的是window,所以this指向Window

<script>
setTimeout(function () {            console.log(this);
        })
 </script>   

2.向外查找 这里的this = window

  <script>
  setTimeout(() => {
            console.log(this);
        })
  </script>   

3.obj对象中的this

1.第一个this中function传入的是window所以this打印的是window,

第二个this向外查找,而对象中的this指向obj,所以this打印的是obj

const obj = {
            aaa() {
                setTimeout(function () {
                    console.log(this);
                })
                setTimeout(() => {
                    console.log(this);
                })
            }
        }

4.obj对象中的this(2)

第三个this中因为function()捕获不到上下文的this,所以传入的是window

打印结果:

第四个[object Object]

第一个[object Window]

第二个[object Window]

第三个[object Window]

第五个[object Object]

 

 const abc ={
            aaa(){
                setTimeout(function(){
                    setTimeout(function(){
                        console.log('第一个'+this); //window
                    })
                    setTimeout(()=>{
                        console.log('第二个'+this);  // window
                    })
                })
                setTimeout(()=>{
                    setTimeout(function(){
                        console.log('第三个'+this); // window
                    })
                    console.log('第四个'+this);
                    setTimeout(()=>{
                        console.log('第五个'+this); //abc
                    })
                })
            }
        
        }
         abc.aaa()
posted @ 2021-06-22 18:24  ajaXJson  阅读(53)  评论(0编辑  收藏  举报