js物件導向編程:this到底代表什嗎?

來源:互聯網
上載者:User

在js中this的用法很讓人迷惑,有些像Java或者C#中的this,但又不完全一樣。按照流行的說法this總是指向調用方法的對象。

1、純粹函數調用。

 function ListCommon2(x) {    this.x=x;alert("this 是 ListCommon2"+(this instanceof ListCommon2));alert("this.constructor"+this.constructor); }                 function test(){                //測試代碼var t1=ListCommon2("燒水");   var t2=new ListCommon2("燒水2");     }
經過測試發現,

如果不使用new,也就是var t1=ListCommon2("燒水");這樣調用,this是全域對象Window對象,

如果使用new,也就是var t2=new ListCommon2("燒水2");;這樣調用,this就變成了new出來的執行個體對象的應用,也就是 t2,

看來和調用方式也是有關係的。

2、作為方法調用,那麼this就是指執行個體化的對象。

 function ListCommon2(x) {    this.x=x;    this.Do=function(x)//特權方法 執行個體方法{  alert("this 是 ListCommon2"+(this instanceof ListCommon2));    alert("this.constructor"+this.constructor);} }       ListCommon2.prototype.Do2=function()//執行個體方法  {        alert("this 是 ListCommon2"+(this instanceof ListCommon2));    alert("this.constructor"+this.constructor);  }               function test(){                //測試代碼var t1=ListCommon2("燒水");//t1.Do();調用錯誤//t1.Do2();調用錯誤   var t2=new ListCommon2("燒水2");   t2.Do();   t2.Do2();     }

經過測試發現,不管是特權方法類型的執行個體方法,還是原型類型的執行個體方法,this都指向了當前新建立的對象。

3 apply,call調用

apply的第一個參數就是this,如果沒有傳遞this就是全域對象。

改變this的方法,通過new可以改變,使用call和apply也可以改變

4 setTimeout中的this

 function ListCommon2(x) {    this.x=x;    this.Do=function(x)//特權方法 執行個體方法{  window.setTimeout(function(){   alert("this 是 ListCommon2"+(this instanceof ListCommon2));      alert("this.constructor"+this.constructor);  },100); } }       ListCommon2.prototype.Do2=function()//執行個體方法  {     window.setTimeout(function(){   alert("this 是 ListCommon2"+(this instanceof ListCommon2));      alert("this.constructor"+this.constructor);  },100);        }               function test(){                //測試代碼   var t2=new ListCommon2("燒水2");   t2.Do();   t2.Do2();     }

測試發現setTimeout中的this也是全域對象Window對象,當然這樣的例子還有很多,感覺應該是執行個體化的對象,可實際上卻不是。因此需要注意。


參考文章

js中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.