1 (function ($) { 2 function guid(g) { 3 var arr = new Array(); //存放32位数值的数组 4 if (typeof (g) == "string") { //如果构造函数的参数为字符串 5 initializeByString(arr, g); 6 } else { 7 initializeByOther(arr); 8 } 9 //返回一个值,该值指示 Guid 的两个实例是否表示同一个值。10 this.equals = function (o) {11 if (o && o.isGuid()) {12 return this.toString() == o.toString();13 }14 else {15 return false;16 }17 }18 //Guid对象的标记19 this.isGuid = function () {20 return /^[0-9a-fA-F]{32}?$|^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}?$/.test(this);21 }22 //返回 Guid 类的此实例值的 String 表示形式。23 this.toString = function (format) {24 if (typeof (format) == "string") {25 if (format == "N" || format == "D" || format == "B" || format == "P") {26 return toStringWithFormat(arr, format);27 } else {28 return toStringWithFormat(arr, "D");29 }30 }31 else {32 return toStringWithFormat(arr, "D");33 }34 }35 //由字符串加载36 function initializeByString(arr, g) {37 g = g.replace(/\{|\(|\)|\}|-/g, "");38 g = g.toLowerCase();39 if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {40 initializeByOther(arr);41 } else {42 for (var i = 0; i < g.length; i++) {43 arr.push(g[i]);44 }45 }46 }47 //由其他类型加载48 function initializeByOther(arr) {49 var i = 32;50 while (i--) {51 arr.push("0");52 }53 }54 /*55 根据所提供的格式说明符,返回此 Guid 实例值的 String 表示形式。56 N 32 位: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx57 D 由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx58 B 括在大括号中、由连字符分隔的 32 位数字:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}59 P 括在圆括号中、由连字符分隔的 32 位数字:(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)60 */61 function toStringWithFormat(arr, format) {62 switch (format) {63 case "N":64 return arr.toString().replace(/,/g, "");65 case "D":66 var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);67 str = str.replace(/,/g, "");68 return str;69 case "B":70 var str = toStringWithFormat(arr, "D");71 str = "{" + str + "}";72 return str;73 case "P":74 var str = toStringWithFormat(arr, "D");75 str = "(" + str + ")";76 return str;77 default:78 return new Guid();79 }80 }81 }82 $.extend({ guidEx: guid });83 $.extend($.guidEx, {84 enpty: function () {85 return new guid();86 },87 newGuid: function () {88 var g = "";89 var i = 32;90 while (i--) {91 g += Math.floor(Math.random() * 16.0).toString(16);92 }93 return new guid(g);94 },95 isGuid: function (g) {96 return /^[0-9a-fA-F]{32}?$|^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}?$/.test(g);97 }98 });99 })(jQuery);