JavaScript中的方法調用詳細介紹,javascript詳細介紹

來源:互聯網
上載者:User

JavaScript中的方法調用詳細介紹,javascript詳細介紹

JavaScript中,如果function屬於一個對象,那麼通過對象來訪問該function的行為稱之為“方法調用”。與普通的函數調用不同的是,在進行方法調用時,function中的this指代將發生變化 — this將指代用於調用該function的對象(該對象將成為方法調用的invocation context):


複製代碼 代碼如下:
var x = 99;
var sample = {
  x:1,
  act:function(a){
    this.x = a*a;//assign value to sample's x, not global object's x.
  }
}
sample.act(6);
console.log(sample.x);//36
console.log(x);//99


與訪問對象中的property一樣,除了使用點號操作符,JavaScript中還可以通過使用中括弧操作符來進行方法調用:


複製代碼 代碼如下:
//other ways to invoke method
sample["act"](7);
console.log(sample.x);//49


對於JavaScript中的function,一個比較有趣的行為是可以在function中嵌入function(閉包)。在進行方法調用時,如果方法function中有嵌入的function,那麼這個嵌入的function中的代碼可以訪問到外部的變數值:


複製代碼 代碼如下:
//nested function can access variable outside of it.
var y = 88;
var sample2 = {
  y:1,
  act2:function(a){
    this.y = inner();
    function inner(){
      return a*a;
    }
  }
}
sample2.act2(8);
console.log(sample2.y);//64
console.log(y);//88


不過,與直覺相反的是,嵌入function中的代碼無法從外部繼承this;也就是說,在嵌入的function中,this指代的並不是調用方法的對象,而是全域對象:


複製代碼 代碼如下:
//nested function does not inherit "this". The "this" in nested function is global object
var sample3 = {
  act3:function(){
    inner();
    function inner(){
      console.log(this);//window object
    }
  }
}
sample3.act3();


如果確實需要在嵌入function中訪問到調用方法的對象,可以在外部function中將this值儲存到一個變數中:


複製代碼 代碼如下:
//pass "this" to nested function
var sample4 = {
  act4:function(){
    var self = this;
    inner();
    function inner(){
        console.log(self);//Object {act4=function()}
    }
  }
}
sample4.act4();

聯繫我們

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