前端-关于this的指向问题

132 阅读2分钟

1,关于普通的this指向

单独的this ,指向window这个对象

          var age = 22;
          console.log(this.age); 
     //我们不难看出看这里的this的上下文 看的话指向的window这个对象

2,全局函数中的this指向

       function demo1() {
         console.log(this);    //this ->window   
        }
       demo1(); 
   // 在严格模式下
   function demo2() {
           'use strict';
          console.log(this);   //this -> undefined   
        }
       demo2();

3, 立即执行函数this指向

   (function () {
           console.log(this);  //this -> window
        })();

4,构造函数中的this,指向new生成的实例对象

   function Star(name,hobby) {
       this.name = name
       this.hobby = hobby;
             
         };
        var cai = new Star('蔡徐坤','篮球');
        console.log(cai.hobby); 

5,用call 与 apply 的方式调用函数

var abc =  {

             name : 'ww'
         }
           function demo() {
               console.log(this);
              
           }
           demo.call('abc')   //指向abc这个对象
          demo.call(null)    //this ->window
          demo.call(undefined)   //this ->window

小提示:因为call 与 apply的第一个参数都可以改变this的指向,所以就不演示appiy啦

6,定时器中的this,指向window

 window.setTimeout(function() {
              console.log(this); // this  ->window
  
          }, 1000);

7,元素绑定事件,事件触发,执行函数中的this指向当前元素

 let btn = document.querySelector('button') 
          btn.addEventListener('click',function() {
              console.log(this);    // 输出的是<button>按钮</button>
          }) 

8,函数调用时,绑定bind,那么函数中的this 指向bind中绑定的元素

 let o = {
               name : 'lala'
           }
          let btn = document.querySelector('button') 
          btn.addEventListener('click',function() {
              console.log(this);    // 输出的是 {name: "lala"}
          }.bind(o)) 

9, 对象方法中的this ,该方法被哪个对象调用了,那么方法中的this就指向该对象

   var o = {
             sayHi: function() {
                 console.log(this);
             }
         }
         o.sayHi();   //this -> o
         //如果把o.sayHi载给一个变量
         var test = o.sayHi;
         //再调用,此事this指向 window
         test();    //this ->window 

10,箭头函数中的this,指向它定义的地方(通过call 等都不能改变指向)

   var o = {
             age : 90
         }
         let obj = {
            age: 20,
            say: () =>console.log(this.age)  //undefined
        }
        obj.say(); 
        const ss =() => {
            console.log(this.age)
        };
        ss.bind(o);

以上就是你们的小菜菜学姐跟不清楚this指向的小宝贝们的总结的哦,这也是我的第一篇文章,希望能帮助到大家哦~~顺便祝大家新年快乐!