善用Javascript的prototype属性,自定更多实用工具函数

 1 //利用Prototype属性为String对象添加一个方法
 2 
 3 String.prototype.format = function()
 4 {
 5     var args = arguments;
 6     return this.replace(/\{(\d+)\}/g,                
 7         function(m,i){
 8             return args[i];
 9         });
10 }
11 
12  
13 
14 //利用js对象的特性,动态添加对象属性并赋于方法体,实现类同于C#、JAVA等语言的String.format方法。
15 
16 String.format = function() {
17     if( arguments.length == 0 )
18         return null;
19 
20     var str = arguments[0]; 
21     for(var i=1;i<arguments.length;i++) {
22         var re = new RegExp('\\{' + (i-1) + '\\}','gm');
23         str = str.replace(re, arguments[i]);
24     }
25     return str;
26 }
27 
28 var a = "I Love {0}, and You Love {1},Where are {0}! {4}";
29 alert(String.format(a, "You","Me"));
30 
31 alert(a.format("You","Me"));
posted @ 2012-09-21 05:51  EKO.KL  阅读(325)  评论(0)    收藏  举报