在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的總結