JavaScript arguments對象

來源:互聯網
上載者:User

arguments 對象
JavaScript 中每個函數內都能訪問一個特別變數 arguments。這個變數維護著所有傳遞到這個函數中的參數列表。
    注意: 由於 arguments 已經被定義為函數內的一個變數。
    因此通過 var 關鍵字定義 arguments 或者將 arguments 聲明為一個形式參數,
    都將導致原生的 arguments 不會被建立。
arguments 變數不是一個數組(Array)。
儘管在文法上它有數組相關的屬性 length,但它不從 Array.prototype 繼承,實際上它是一個對象(Object)。
因此,無法對 arguments 變數使用標準的數組方法,比如 push, pop 或者 slice。
雖然使用 for 迴圈遍曆也是可以的,但是為了更好的使用數組方法,最好把它轉化為一個真正的數組。
轉化為數組
下面的代碼將會建立一個新的數組,包含所有 arguments 對象中的元素。
Array.prototype.slice.call(arguments);
這個轉化比較慢,在效能不好的代碼中不推薦這種做法。
傳遞參數
下面將參數從一個函數傳遞到另一個函數,是推薦的做法。
function foo() {
    bar.apply(null, arguments);
}
function bar(a, b, c) {
    // do stuff here
}
另一個技巧是同時使用 call 和 apply,建立一個快速的解除綁定定封裝器。
function Foo() {}
Foo.prototype.method = function(a, b, c) {
    console.log(this, a, b, c);
};
// Create an unbound version of "method"
// 輸入參數為: this, arg1, arg2...argN
Foo.method = function() {
    // 結果: Foo.prototype.method.call(this, arg1, arg2... argN)
    Function.call.apply(Foo.prototype.method, arguments);
};
譯者註:上面的 Foo.method 函數和下面代碼的效果是一樣的:
Foo.method = function() {
    var args = Array.prototype.slice.call(arguments);
    Foo.prototype.method.apply(args[0], args.slice(1));
};
自動更新
arguments 對象為其內部屬性以及函數形式參數建立 getter 和 setter 方法。
因此,改變形參的值會影響到 arguments 對象的值,反之亦然。
function foo(a, b, c) {
    arguments[0] = 2;
    a; // 2                                                          

    b = 4;
    arguments[1]; // 4

    var d = c;
    d = 9;
    c; // 3
}
foo(1, 2, 3);
效能真相
arguments 對象總會被建立,除了兩個特殊情況 - 作為局部變數聲明和作為形式參數。
而不管它是否有被使用。
arguments 的 getters 和 setters 方法總會被創佳;因此使用 arguments 對效能不會有什麼影響。
除非是需要對 arguments 對象的屬性進行多次訪問。
ES5 提示: 這些 getters 和 setters 在strict 模式下(strict mode)不會被建立。

聯繫我們

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