JS中精選this關鍵字的指向規律你記住了嗎

來源:互聯網
上載者:User

標籤:構造   2.3   class   blog   call   val   ima   cal   size   

  1.首先要明確:          誰最終調用函數,this指向誰          this指向的永遠只可能是對象!!!!!          this指向誰永遠不取決於this寫在哪,而取決於函數在哪裡調用!          this指向的對象,我們稱之為函數的上下文context,也叫做函數的調用者是誰!  2.this指向的規律(與函數調用的方式息息相關)   this指向的情況取決於函數調用的方式有哪些(總結如下):      2.1.通過函數名()直接調用--this 指向window;                     
         function func(){            console.log(this);             }
  func();

      2.2.通過對象.函數名()調用的--this指向這個對象

                狹義對象: this指向--obj    

                  var obj={                         name:"obj",                         func1:func                         };                   obj.func1();

 

                 廣義對象: this指向--div

 document.getElementById("div").onclick=function(){      this.style.backgroundColor="red";      }

    2.3. this指向——數組arr

var arr=[func,1,2,3];     arr[0]();

    2.4.函數作為window內建函數的回呼函數調用,this指向window setInterval,setTimout等

setInterval(func,1000);            setTimeout(func,1000)
   2.5.函數作為建構函式,用new關鍵字調用時:this指向新定義的對象obj    var obj=new func();

  2.6.  通過call、apply、bind調用,this指向我們規定的對象。

  Func.call(obj,參數一,參數2,參數3.。。。)

  Func.allply(obj,[ 參數一,參數2,參數3.。。。])

   Func.bind(obj)( 參數一,參數2,參數3)   var f = func.bind(obj).   f(…….);

    小試牛刀:
var fullname = ‘John Doe‘;        var obj = {           fullname: ‘Colin Ihrig‘,           prop: {              fullname: ‘Aurelio De Rosa‘,              getFullname: function() {                 return this.fullname;              }           }        };        console.log(obj.prop.getFullname()); // Aurelio De Rosa        //函數最終調用者:obj.prop  this--->obj.prop                 var test = obj.prop.getFullname;                 console.log(test());  // John Doe        // 函數最終調用者: 函數() window  this-->window

 

JS中精選this關鍵字的指向規律你記住了嗎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.