Javascript學習筆記之函數篇(四):arguments 對象,學習筆記arguments

來源:互聯網
上載者:User

Javascript學習筆記之函數篇(四):arguments 對象,學習筆記arguments

每一個 Javascript 函數都能在自己範圍內訪問一個特殊的變數 - arguments。這個變數含有一個傳遞給函數的所有參數的列表。
arguments 對象不是一個數組。儘管在文法上它跟數組有相同的地方,例如它擁有 length 屬性。但它並不是從 Array.prototype 繼承而來,實際上,它就是一個對象。
因此,我們不能直接對 arguments 使用一些數組的方法,例如 push, pop 或 slice 等。 所以為了使用這些方法,我們就需要將其轉換為一個真正的數組。

轉化為數組

下面的代碼將會返回一個包含 arguments 對象所有元素的數組。

Array.prototype.slice.call(arguments);
由於轉化的速度很慢,所以在效能要求嚴格的程式中不建議這樣做。

傳遞參數

下面是一種比較推薦的方法,將 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"
// It takes the parameters: this, arg1, arg2...argN
Foo.method = function() {
    // Result: Foo.prototype.method.call(this, arg1, arg2... argN)
    Function.call.apply(Foo.prototype.method, arguments);
};

函數形參和 arguments 屬性的關係

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 對象總是會被建立。
由於 getter 和 setter 方法總是會隨著 arguments 對象的建立而建立,因此使用 arguments 對效能本身幾乎沒有影響。
然而,有一種情形會嚴重影響 Javascript 的效能,那就是使用 arguments.callee。

複製代碼 代碼如下:
function foo() {
    arguments.callee; // do something with this function object
    arguments.callee.caller; // and the calling function object
}
function bigLoop() {
    for(var i = 0; i < 100000; i++) {
        foo(); // Would normally be inlined...
    }
}

在上述代碼中,foo 函數不再是一個簡單的內聯擴充,因為它需要知道它自身以及它的調用者(caller)。這不僅抵消了內聯擴充所帶來的效能提升,同時也破壞了函數的封裝性,因為函數本身可能需要依賴於一個特定的調用背景。
因此,建議大家盡量不要使用 arguments.callee。

以上就是關於Javascript arguments 對象的全部內容了,小夥伴們是否瞭解透徹呢,簡單的說

arguments指函數的參數對象(指實際傳入的參數)
arguments.length指函數的參數對象的長度
arguments[i]指第i個參數的值(第一個為0)

聯繫我們

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