有一個叫做arguments
的特殊對象,它在函數被調用時被創建。它是一個數組狀物體表示傳遞到一個函數的參數:
它可用於這樣的:
test();
// no arguments passed, but it still gets created:
// arguments.length = 0
// arguments >> []
test(a);
// ONE argument passed:
// arguments.length = 1
// arguments >> [a]
test(a,b,c,d);
// FOUR arguments passed:
// arguments.length = 4
// arguments >> [a,b,c,d]
知道了這一點,可調用一回調與在傳遞的參數的其餘部分使用apply
這樣父功能:
function test(callback) {
callback.apply(null, Array.prototype.slice.call(arguments, 1));
}
// arguments passed into test are available in the function scope when
// .slice is used here to only pass the portion of the arguments
// array relevant to the callback (i.e. any arguments minus the
// first argument which is the callback itself.)
//
// N.B. The arguments object isn't an array but an array like object so
// .slice isn't available on it directly, hence .call was used here)
可能是值得閱讀起來:
爲什麼不t簡單地調用如下測試:'test(callback_b('what b have to say'))' – malarres
@malarres它仍然會如果條件爲false,則執行'callback_b' – qslcna
@malarres:**和**它會在'test'之前執行'callback_b' * first *。 –