这是一个独立的验证函数,您可以在任何函数中使用它来检查传递的参数是否存在和使用匈牙利符号的类型正确性:
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 将有一种一次性传递所有参数的方法,但是这只适用于未来的浏览器,而长手方式适用于当时、现在和永远的浏览器......
编辑:更新基于注释的验证例程,使其更加强大,将文档、输入、表单、数组、正则表达式、日期和对象添加到匈牙利符号验证例程,现在也可以跨窗口对象工作。