javascript之this

來源:互聯網
上載者:User

標籤:color   javascrip   nbsp   call   調用   對象   直接   返回   原型   

總結一句話:javascript函數裡的this,始終指向調用該函數的直接對象。當然通過apply(),call(),bind()這幾個方法可以更改this除外

執行個體1:alert(this === window);  //true            調用該函數的直接對象是全域window

 

執行個體2:var test = function() { alert(this === window)}; test(); //true          調用該函數的直接對象仍是全域window

 

執行個體3:var test = function() { alert(this === window)}; new test(); //false       因為new關鍵字建立了一個Null 物件,相當於由這個Null 物件作為建構函式調用的直接對象,此時this就不是指向window而是指向Null 物件,並將Null 物件進行初始化作為傳回值。

 

執行個體4:var test = { ‘a‘: 1, ‘b‘: function(){ alert(this === test);}}; test.b() //true     這是test作為函數test.b調用的直接對象

 

執行個體5: var test = {‘a‘: 1, ‘b‘: {‘b1‘: function(){ alert(this === test.b); }}}; test.b.b1();  //true   這時test.b作為函數test.b.b1調用的直接對象 

 

執行個體6: var test = function(){ var inner = function(){ alert(this === window);} inner(); }; test();  //true   類似閉包函數裡的this,無論多少層,調用函數的直接對象始終為全域window

 

執行個體7: 關於原型鏈繼承   var test = function(){};  var test2 = function(){ this.a = function(){ alert(this === p1);}}; var p2 = new test2(); test.prototype = p2; test.prototype.constructor = test;var p1 = new test(); p1.a(); //true      此時p1作為函數p2.a調用的直接對象

 

執行個體8:dom節時間點事件監聽函數的this  <div onclick="shw(this)"></div>   此時的this指向節點元素對象

 

javascript之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.