DIV CSS 佈局教程網

JavaScript 內建物件 arguments 詳解
編輯:JavaScript基礎知識     

一、什麼是 arguments

arguments 是 JavaScript 裡一個古怪卻重要的內建物件,常被忽略,但所有主要 JS 函式庫都靠它運作,因此值得每位開發者熟悉。

每個函數都有屬於自己的 arguments 物件,它包含呼叫時傳入的參數。它不是真正的陣列——用 typeof 檢測會得到 'object'。雖然我們能用 length 與索引取值,但陣列的 push、pop 等方法並不適用。

二、打造靈活的函數

看起來 arguments 用途有限,實際上非常有用。藉由它,函數可以接收數量不定的參數。以下改寫自 Dean Edwards 的 base2 函式庫:

function format(string) {
    var args = arguments;
    var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
    return String(string).replace(pattern, function(match, index) {
        return args[index];
    });
}

我們提供一個模板字串,可用「%1」到「%9」作為佔位符,再傳入其他參數填入:

format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");
// 回傳 "And the papers want to know whose shirt you wear"

值得注意的是,定義時只規定了 string 一個參數,但 JS 允許傳入任意數量的參數,arguments 都能承接。

三、把 arguments 轉成真陣列

雖然 arguments 不是真正的陣列,卻能輕易轉成標準陣列再操作:

var args = Array.prototype.slice.call(arguments);

四、預置參數以建立函數

arguments 讓我們能實作各種高階技巧。以下 makeFunc 函數接收一個函數參照與其參數,回傳一個匿名函數去呼叫它,並自動補上預設參數:

function makeFunc() {
    var args = Array.prototype.slice.call(arguments);
    var func = args.shift();
    return function() {
        return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
    };
}

第一個參數是要呼叫的函數參照,從陣列中移出後,makeFunc 回傳的匿名函數會把原始參數串接上呼叫時傳入的參數。你可以用它固定模板:

var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");

majorTom("stepping through the door");
majorTom("floating in a most peculiar way");
// 分別回傳:
// "This is Major Tom to ground control. I'm stepping through the door."
// "This is Major Tom to ground control. I'm floating in a most peculiar way."

五、建立引用自身的函數

arguments 還有個實用特性:callee。它包含建立該 arguments 物件的函數參照,讓匿名函數能方便地指向自身。以下 repeat 函數接收一個函數與兩個數字(重複次數、間隔毫秒):

function repeat(fn, times, delay) {
    return function() {
        if (times-- > 0) {
            fn.apply(null, arguments);
            var args = Array.prototype.slice.call(arguments);
            var self = arguments.callee;
            setTimeout(function(){ self.apply(null, args) }, delay);
        }
    };
}

repeat 用 arguments.callee 取得指向自身的參照,讓匿名函數能再次呼叫自己。搭配一個簡單的 comms 函數:

function comms(s) {
    alert(s);
}

var somethingWrong = repeat(comms, 3, 2000);
somethingWrong("Can you hear me, major tom?");

如此便能每隔 2 秒重複 alert 三次。arguments 雖不常用、略顯古怪,卻充滿驚喜,值得深入了解。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved