this指向問題的經典場景

THIS常用場景

1、以函數形式調用,this指向window

function fn(m,n){
   m=2;
   n=3;
console.log(this.m,n);//undefined,this指向了window
}
fn();

2、以方法形式調用,this指向調用方法的那個對象

box.onclick =function(){
    this.style.backgroundColor = "red"; //this指向box,box顏色爲紅色
}

3、構造函數調用,this指向實例的對象

function Person(age , name ) {
         this.a = age ;
         this.b = name;
         console.log(this)  // 此處 this 分別指向 Person 的實例對象 p1 p2
     }
    var p1 = new Person(18, 'zs')
    var p2 = new Person(18, 'ww')
 控制檯輸出:
 Person {a: 18, b: "zs"}
 Person {a: 18, b: "ww"}
 

4、使用window對象的方法使,指向window

var box =document.getElementById("box");
box.onclick =function(){
    setTimeout(function(){
       this.style.backgroundColor="yellow"
    },1000)
}
//報錯,因爲setTimeout是window的一個方法.解決方法可以在14行加上var me=this,然後在本行用me.style調用

更改錯誤,使box顏色爲yellow

var box =document.getElementById("box");
box.onclick =function(){
    var me = this;//box調用了這個方法,此時的this指向box,此操作將指向box的this賦給me,則得到的me的指向爲指向this
    setTimeout(function(){
       me.style.backgroundColor="yellow"//此時的me.style就指的是box的style
    },1000)
}

5、多重場景改變this指向

box.onclick=function(){ 
     function fn1(){ 
          console.log(this); 
     } 
     fn1(); //事件觸發了fn1,在函數內部,以函數形式調用this依舊指向window
     console.log(this);//事件處理函數中的this,該事件由誰觸發,this就指向誰
};
 控制檯輸出:
 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
 <div id = "box">box</div>
 
box.onclick=function(){ 
    var me = this;
    function fn1(){ 
        console.log(me); 
    } 
   fn1(); //事件觸發了fn1,me指向box,所以console的是box
   console.log(this);//事件處理函數中的this,該事件由誰觸發,this就指向誰
 };
 控制檯輸出:
 <div id = "box">box</div>
 <div id = "box">box</div>

6、call和apply改變this指向

var person={
      name : "lili",
      age: 21
    };
function aa(x,y){
      console.log(x,y);
      console.log(this.name);
    }
  aa.call(person,4,5);
控制檯輸出
//4 5
//lili
使用call,this指向call後面緊跟的元素,this就指向person
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章