这里要说的是,你可以使用任何功能检查通过一个独立的验证函数使用匈牙利符号的存在和类型正确性的论据:
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数组中获取每个参数的名称的方法。 –