javascript---遇到關於this的相關問題(解決this)(持續更新中...)

來源:互聯網
上載者:User

1、在原型中使用this

<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script type="text/javascript">window.onload=function  () {function a(){ this.name="a"; this.sex="男"; this.num=0; } a.prototype.count=function(){ this.num+=1; alert(this.num); if(this.num>10){return;} //下面用四種方法測試,一個一個輪流測試。 //setTimeout("this.count()",1000);//A:當下面的x.count()調用時會發生錯誤:對象不支援此屬性或方法。 //setTimeout("count()",1000);//B:錯誤顯示:缺少對象 //setTimeout(count,1000);//C:錯誤顯示:'count'未定義 //下面是第四種 var self=this; setTimeout(function(){self.count();},1000);//D:正確 } var x=new a(); x.count(); }</script></head><body></body></html>

錯誤分析:
A:中的this其實指是window對象,並不是指當前執行個體對象
B:和C:中的count()和count其實指的是單獨的一個名為count()的函數,但也可以是window.count(),因為window.count()可以省略為count()

D:將變數self指向當前執行個體對象,這樣js解析引擎就不會混肴this指的是誰了。 

另外:setTimeout()傳入this的時候,當然指的是它所屬的當前對象window了(因為setTimeout()是window的一個方法!!!)


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.