JS this指向

來源:互聯網
上載者:User

標籤:傳遞   定義   type   上下文   str   結合   另一個   導致   javascrip   

JS中,this的值取決於調用的模式,而JS中總有4中調用模式:

1.方法調用模式:

當一個函數被儲存為對象的一個屬性時,我們稱它為一個方法,當一個當法被調用時,this指向改對象,如:

var obj = {

  value : 1,

  getValue : function(){

    alert(this.value);

  }

};

obj.getValue(); //輸出1,此時的this指向obj 

注意: 該模式下,this到對象的綁定發生在方法被調用的時候。

2.函數調用模式:

當一個函數並非一個對象的屬性時,它被當作一個函數來調用,此時this指向全域對象(window),如:

window.value = 1;

function getValue (){

  alert(this.value);

};

getValue(); //輸出1,此時的this指向window 

3.構造器調用模式:

結合new首碼調用的函數被稱為構造器函數,此時的this指向該構造器函數的執行個體對象,如:

function show(val){

  this.value = val;

};

show.prototype.getVal = function(){

  alert(this.value);

};

var func = new show(1);

func.getVal(); // 輸出1

alert(func.value) //輸出1

// 從上面的結果,可以看出,此時的this指向了func對象

4.apply/call 調用模式

apply 和 call 方法可以讓我們設定調用者中的this指向誰,如:

var fun = function(str){

  this.status = str;

}

fun.prototype.getStatus = function(){

  alert(this.status);

}

var obj = {

  status : "loading"

};

fun.prototype.getStatus.apply(obj); //輸出”loading“ ,此時getStatus方法中的this指向了obj

補充說明:

call方法:

文法:call( [ thisObj [ , arg1 [ , arg2 [ ,  [ , .argN] ] ] ] ] )

定義:調用一個對象的一個方法,以另一個對象替換當前對象。

說明:call方法可以用來代替另一個對象調用一個方法。call方法可將一個函數的物件內容從初始的上下文改變成由thisObj指定的新對象。

如果沒有提供thisObj參數,那麼Global對象被用作thisObj。

apply方法:

文法:apply( [ thisObj [ , argArray ] ] )

定義:應用某一對象的一個方法,用另一個對象替換當前對象。

說明:

如果argArray不是一個有效數組或者不是arguments對象,那麼將導致一個TypeError

如果沒有提供argArray 和 thisObj 任何一個參數,那麼Global對象將被用作thisObj,並且無法被傳遞任何參數

取自 : 《JavaScript 語言精髓》

 

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.