- /*******************************************************************************
- * 函数重载和类型检测
- */
- /** *********************************使用一个函数检测传入的参数类型和数量******************************************** */
- function strict(types, args) {
- // 判断类型和参数长度是匹配
- if (types.length != args.length) {
- throw "Exception number of type " + types.length + "!= number of args"
- + args.length;
- }
- for (var i = 0; i < args.length; i++) {
- if (types[i] != args[i].constructor)
- {
- throw "Exception type " + types[i].name + "!="
- + args[i].constructor.name;
- }
- }
- }
- function userList(prefix, num, user) {
- strict([String, Number, Array], arguments);
- for (var i = 0; i < num; i++) {
- alert("prefix: " + user[i]);
- }
- }
- userList("user类型测试", 3, ["张三", "李四", "王五"]);
- //output prefix:张三 prefix:李四 prefix:王五
- //该片段来自于http://www.codesnippet.cn/detail/1611201514000.html
来源: http://www.codesnippet.cn/detail/1611201514000.html