欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript學(xué)習(xí)筆記之函數(shù)篇(四):arguments 對象

 更新時間:2014年11月23日 10:53:59   投稿:hebedich  
JavaScript中arguments函數(shù)對象是該對象代表正在執(zhí)行的函數(shù)和調(diào)用它的函數(shù)的參數(shù)。JavaScript 函數(shù)中 arguments 為特殊對象,無需明確指出參數(shù)名,就能訪問它們。

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

轉(zhuǎn)化為數(shù)組

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

Array.prototype.slice.call(arguments);
由于轉(zhuǎn)化的速度很慢,所以在性能要求嚴(yán)格的程序中不建議這樣做。

傳遞參數(shù)

下面是一種比較推薦的方法,將 arguments 對象從一個函數(shù)傳遞到另一個函數(shù)。

復(fù)制代碼 代碼如下:

function foo() {
    bar.apply(null, arguments);
}
function bar(a, b, c) {
    // do stuff here
}

另外還有一個比較巧妙的方法,就是同時使用 call 和 apply 快速創(chuàng)建一個解綁的外層方法。

復(fù)制代碼 代碼如下:

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);
};

函數(shù)形參和 arguments 屬性的關(guān)系

arguments 對象為它自身屬性和函數(shù)的形參都創(chuàng)建了 getter 和 setter 方法。
因此,修改函數(shù)的形參會影響對應(yīng)的 arguments 對象的屬性值,反之亦然。

復(fù)制代碼 代碼如下:

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 只在兩種情況下不會被創(chuàng)建,一是在函數(shù)內(nèi)部被聲明為局部變量,二是當(dāng)做函數(shù)的形參。其他情況,arguments 對象總是會被創(chuàng)建。
由于 getter 和 setter 方法總是會隨著 arguments 對象的創(chuàng)建而創(chuàng)建,因此使用 arguments 對性能本身幾乎沒有影響。
然而,有一種情形會嚴(yán)重影響 Javascript 的性能,那就是使用 arguments.callee。

復(fù)制代碼 代碼如下:

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 函數(shù)不再是一個簡單的內(nèi)聯(lián)擴展,因為它需要知道它自身以及它的調(diào)用者(caller)。這不僅抵消了內(nèi)聯(lián)擴展所帶來的性能提升,同時也破壞了函數(shù)的封裝性,因為函數(shù)本身可能需要依賴于一個特定的調(diào)用背景。
因此,建議大家盡量不要使用 arguments.callee。

以上就是關(guān)于Javascript arguments 對象的全部內(nèi)容了,小伙伴們是否了解透徹呢,簡單的說

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

相關(guān)文章

最新評論