這裏要說的是,你可以使用任何功能檢查通過一個獨立的驗證函數使用匈牙利符號的存在和類型正確性的論據:
function fnDrawPrism(length, numWidth, intHeight){
//If any of these parameters are undefined, throw an error that lists the missing parameters.
// you can cut-and-past the declaration line to fill out 90% of the validation call:
validate(fnDrawPrism, length, numWidth, intHeight);
return length * numWidth * intHeight;
}
// this is cut-and-pasted into a file somewhere, edit to add more types or stricter checking
function validate(args){
var fn = args, actuals = [].slice.call(arguments, 1),
hung = {int: "Number", num: "Number", str: "String", arr: "Array",
obj: "Object", inp: "HTMLInputElement", dt: "Date", bln: "Boolean",
rx: "RegExp", frm: "HTMLFormElement", doc: "HTMLDocument"},
names = String(fn).split(/\s*\)\s*/)[0].split(/\s*\(\s*/)[1].split(/\s*\,\s*/),
mx = names.length, i = 0;
if(!fn.name)
fn.name = String(fn).split(/\s*(/)[0].split(/\s+/)[1] || 'anon';
for(i; i < mx; i++){
if(actuals[i] === undefined)
throw new TypeError("missing arg #" + i + " in " + fn.name + " - " + names[i]);
var hint = hung[names[i].split(/[A-Z]/)[0]],
got = toString.call(actuals[i]).split(/\W/)[2];
if(hint && got !== hint)
throw new TypeError("Wrong type in argument #" + i + " of " + fn.name + " - " + names[i] + ". Got: " + got + ", Expected: " + hint);
}
//try it out:
fnDrawPrism(1); //! missing arg #1 in fnDrawPrism - numWidth
fnDrawPrism(1,4); //! missing arg #2 in fnDrawPrism - intHeight
fnDrawPrism(1,2,3); // ok
fnDrawPrism(1,"2",3); //! Wrong type in argument #1 of fnDrawPrism - numWidth. Got: string, Expected: number
你可以這樣做的原因;只是將「參數」傳遞給驗證程序是因爲嚴格模式對參數對象施加了太多的限制以可靠地使用它。 Ecma6將有一種方法可以一次性傳遞所有參數,但那樣只會在未來的瀏覽器上運行,而長時間的瀏覽器則可以在瀏覽器中運行,然後,現在和永遠......
編輯:基於註釋更新驗證例程,使其更加強大一點,將文檔,輸入,表單,數組,正則表達式,日期和對象添加到匈牙利符號驗證例程中,該例程現在也適用於跨窗口對象。
你不需要'|| (長度==「未定義」)'的一部分,除非你擔心有人可能會打電話給你的功能,實際上故意通過用'fnDrawPrism(「未定義」)'該字符串。 – nnnnnn
你認爲[參數](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments)可以解決你的問題 – aaronman
@aaronman是的,但後來我需要一個從arguments數組中獲取每個參數的名稱的方法。 –