瞭解Js中的this指向

來源:互聯網
上載者:User

標籤:方法   log   func   執行個體   16px   show   ons   style   對象   


  Js中的this對象是在運行時基於函數的執行環境綁定的,其中的this指向很不好理解,一不小心就用錯了位置;。
  this的指向在函數定義的時候是確定不了的,只有函數執行的時候才能確定this到底指向誰,實際上this的最終指向的是那個
調用它的對象。
  
  對於this指向的理解,我分以下幾種情況來說,
this的指向
1、在全域函數中,this等於window:
var name="cyp";

console.log(this);

 

2、當函數被用作為某個對象的方法調用時,this等於哪個對象。


 function show() {       console.log(this);    }   show();

3、建構函式的時候,指向執行個體化對象。

 function Person(name) {        this.name=name;        this.showName=function () {            console.log(this)        }    }    var person1=new Person("cyp");    var person2=new Person("LCX");    person2.showName();

4、不過匿名函數的執行環境具有全域性,因此其this對象通常指向window。


 function fun() {        console.log(this);    }    fun()

5、事件中,this指向觸發這個事件的對象

// html:<input type="button" value="點擊" onclick="fun()">//  JS:document.querySelector("input").onclick=function () {       console.log(this);   }

 



 

瞭解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.