Javascript中的arguments與重載介紹,javascriptarguments

來源:互聯網
上載者:User

Javascript中的arguments與重載介紹,javascriptarguments

因為語言上的設計錯誤,arguments可以被當成一個數組。
複製代碼 代碼如下:
function zero () {
    console.log(arguments[0]);
}

也會有
複製代碼 代碼如下:
function zero () {
  for(var i=0;i<arguments.length;i++){
     console.log(arguments[i]);
  }
}

它利用了Javascript的一個事實,即Javasc

而這裡的arguments變數給實參提供了一個類似數組的介面。因為這裡的arguments的可變參數,我們可以利用這個有意思的東西來做一些有意思的事,比如重載。

Javscript 重載

stackvoerflow上有一個關於重載的問題,於是有了第一個答案
複製代碼 代碼如下:
if (typeof friend === "undefined") {

} else {

}

還有一個答案則是
複製代碼 代碼如下:
switch (arguments.length) {
case 0:
    //Probably error
    break;
case 1:
    //Do something
    break;
case 2:
default: //Fall through to handle case of more parameters
    //Do something else
    break;
}

只是這種方式真的不好看,難道我們的函數最後要變成這樣子的?

複製代碼 代碼如下:
function zero1 (){
    console.log('arguments 1')
};
function zero2 (){
    console.log('arguments 2')
};
function zero () {
  if(arguments.length == 1){
    zero1();
  } else{
    zero2();
  }
}

真的一點都不好看,即使我們換個switch..case,也不好看啊。

Javascript arguments不是一個數組

arguments不是向我們看到的那樣一直是一個數組,有時候可能不是。
複製代碼 代碼如下:
function hello(){
    console.log(typeof arguments);
}

這裡arguments的類型是一個對象,雖然數組的類型也是一個對象,雖然我們可以將之轉換為一個數組
複製代碼 代碼如下:
var args = Array.prototype.slice.call(arguments);

但是這也表明了這不是一個數組,它擁有的只有Array的唯一一個屬性,即length。除此還有

arguments.callee

Reference to the currently executing function.

arguments.caller

Reference to the function that invoked the currently executing function.

arguments.length

Reference to the number of arguments passed to the function.

聯繫我們

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