D类库是以“为当前成熟框架、类库开发辅助类库”的目标而被开发。 因为是辅助类库,所以为了兼容所有其他框架和类库,采用了包装器的方式对对象进行扩展。D类库的最主要的内容是针对js常用内置对象的扩展,比如:String,Number,Array,Date等,这些扩展偏于具体的业务逻辑,比如对String扩展的trim方法、对Date扩展的toStr方法等,都是对一些常用但对象本身不支持且框架类库也不支持或不完整支持的功能扩展。同时通过对应包装器的包装我们可以通过链式方法来操作对象,最后每个包装器都提供了拆箱(即还原为原生对象)方法。故包装器提供的实质是一个装箱、操作、拆箱的过程。 命名空间: 1 var D = {};
部分功能如下: 1. String包装器 代码
1 (function(){
2 //包装String 3 D.str = function(s){ 4 if(! (this instanceof y.str))return new y.str(s); 5 this.val = (s!==undefined) ? s.toString() : ""; 6 }; 7 D.str.prototype = { 8 //删除字符串两边空白 9 trim : function(type){ 10 var types = {0:"(^\\s+)|(\\s+$)",1:"^\\s+",2:"\\s+$"}; 11 type = type || 0; 12 this.val = this.val.replace(new RegExp(types[type],"g"),""); 13 return this; 14 }, 15 //重复字符串 16 repeat : function(n){ 17 this.val = Array(n+1).join(this.val); 18 return this; 19 }, 20 //字符串两边补白 21 padding : function(len,dire,str){ 22 if(this.val.length>=len)return this; 23 dire = dire || 0; //[0代表左边,1代表右边] 24 str = str || " "; //默认为一个空白字符 25 var adder = []; 26 for(var i=0,l = len - this.val.length; i<l;i++){ 27 adder.push(str); 28 } 29 adder = adder.join(""); 30 this.val = dire ? (this.val + adder) : (adder + this.val); 31 return this; 32 }, 33 reverse : function(){ 34 this.val = this.val.split("").reverse().join(""); 35 return this; 36 }, 37 byteLen : function(){ 38 return this.val.replace(/[^\x00-\xff]/g,"--").length; 39 }, 40 unBox : function(){ 41 return this.val; 42 } 43 }; 44 //alert(D.str(" 123 ").trim().repeat(2).padding(10,0,"x").reverse().unBox()); 45 })();
2.Array包装器 代码
1 (function(){
2 //包装Array 3 D.arr = function(arr){ 4 if(!(this instanceof D.arr))return new D.arr(arr); 5 this.val = arr || []; 6 }; 7 D.arr.prototype = { 8 each : function(fn){ 9 for(var i=0,len=this.val.length;i<len;i++){ 10 if(fn.call(this.val[i])===false){ 11 return this; 12 } 13 } 14 return this; 15 }, 16 map : function(fn){ 17 var copy = []; 18 for(var i=0,len = this.val.length;i<len;i++){ 19 copy.push(fn.call(this.val[i])); 20 } 21 this.val = copy; 22 return this; 23 }, 24 filter : function(fn){ 25 var copy = []; 26 for(var i=0,len=this.val.length;i<len;i++){ 27 fn.call(this.val[i]) && copy.push(this.val[i]); 28 } 29 this.val = copy; 30 return this; 31 }, 32 remove : function(obj,fn){ 33 fn = fn || function(m,n){ 34 return m===n; 35 }; 36 for(var i=0,len = this.val.length;i<len;i++){ 37 if(fn.call(this.val[i],obj)===true){ 38 this.val.splice(i,1); 39 } 40 } 41 return this; 42 }, 43 unique : function(){ 44 var o = {},arr = []; 45 for(var i=0,len = this.val.length;i<len;i++){ 46 var itm = this.val[i]; 47 (!o[itm] || (o[itm]!==itm) )&& (arr.push(itm),o[itm] = itm); 48 } 49 this.val = arr; 50 return this; 51 }, 52 indexOf : function(obj,start){ 53 var len = this.val.length,start = ~~start; 54 start < 0 && (start+= len); 55 for(;start<len;start++){ 56 if(this.val[start]===obj)return start; 57 } 58 return -1; 59 }, 60 lastIndexOf : function(obj,start){ 61 var len = this.val.length,start = arguments.length === 2 ? ~~start : len-1; 62 start = start < 0 ? (start+len) : (start>=len?(len-1):start); 63 for(;start>-1;start--){ 64 if(this.val[start] === obj)return start; 65 } 66 return -1; 67 }, 68 unBox : function(){ 69 return this.val; 70 } 71 }; 72 //alert( D.arr(["123",123]).unique().unBox()); 73 //alert(D.arr([1,2,3]).map(function(i){return ++i;}).filter(function(i){return i>2;}).remove(3).unBox()); 74 })();
3.Number包装器 代码
1 (function(){
2 //包装Number 3 D.num = function(num){ 4 if(!(this instanceof D.num))return new D.num(num); 5 this.val = Number(num) || 0; 6 }; 7 D.num.prototype = { 8 padZore : function(len){ 9 var val = this.val.toString(); 10 if(val.length>=len)return this; 11 for(var i=0,l = len-val.length;i<l;i++){ 12 val = "0" + val; 13 } 14 return val; 15 }, 16 floatRound : function(n){ 17 n = n || 0; 18 var temp = Math.pow(10,n); 19 this.val = Math.round(this.val * temp)/temp; 20 return this; 21 }, 22 unBox : function(){ 23 return this.val; 24 } 25 }; 26 //alert(D.num(3.1235888).floatRound(3).unBox()); 27 })();
4.Date包装器 代码
1 (function(){
2 //包装Date 3 D.date = function(date){ 4 if(!(this instanceof D.date))return new D.date(date); 5 if(!(date instanceof Date)){ 6 var d = new Date(date); 7 this.val = (d == "Invalid Date" || d == "NaN") ? new Date() : new Date(date); 8 }else{ 9 this.val = date; 10 } 11 }; 12 D.date.prototype = { 13 toStr : function(tpl){ 14 var date = this.val,tpl = tpl || "yyyy-MM-dd hh:mm:ss"; 15 var v = [date.getFullYear(),date.getMilliseconds(),date.getMonth()+1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()]; 16 var k = "MM,M,dd,d,hh,h,mm,m,ss,s".split(","); 17 var kv = {"yyyy":v[0],"yy":v[0].toString().substring(2),"mmss":("000"+v[1]).slice(-4),"ms":v[1]}; 18 for(var i=2;i<v.length;i++){ 19 kv[k[(i-2)*2]] = ("0" + v[i]).slice(-2); 20 kv[k[(i-2)*2+1]] = v[i]; 21 } 22 for(var k in kv){ 23 tpl = tpl.replace(new RegExp( k,"g"),kv[k]); 24 } 25 return tpl; 26 }, 27 unBox : function(){ 28 return this.val; 29 } 30 }; 31 //alert(D.date("2017-123-12").toStr("yyyy-MM-dd hh:mm:ss ms-mmss")); 32 // alert(D.date("2017").unBox()); 33 })();
5.最后为了在脱离其他框架类库的情况下D也可以承担dom操作方面的任务,实现了Dom包装器,如下: 代码
1 (function(){
2 //包装Dom 3 D.dom = function(node){ 4 if(!(this instanceof D.dom))return new D.dom(node); 5 if(typeof node === "undefined"){ 6 node = document.body; 7 }else if(typeof node == "string"){ 8 node = document.getElementById(node); 9 !node && (node = document.body); 10 }else{ 11 !node.getElementById && (node = document.body); 12 } 13 this.val = node; 14 }; 15 D.dom.prototype = { 16 inner : function(value){ 17 this.val.innerHTML ? (value = value || "",this.val.innerHTML = value) : (value = value || 0,this.val.value = value); 18 return this; 19 }, 20 attr : function(k,v){ 21 if(typeof k == "object"){ 22 for(var m in k){ 23 this.val[m] = k[m]; 24 } 25 }else{ 26 this.val[k] = v; 27 } 28 return this; 29 }, 30 css : function(k,v){ 31 var style = this.val.style; 32 if(typeof k == "object"){ 33 for(var m in k){ 34 style[m] = k[m]; 35 } 36 }else{ 37 style[k] = v; 38 } 39 return this; 40 }, 41 addClass : function(cls){ 42 var clsName = " " + this.val.className + " "; 43 (clsName.indexOf(" " + cls + " ")==-1) && (clsName = (clsName + cls).replace(/^\s+/,"")); 44 this.val.className = clsName; 45 return this; 46 }, 47 removeClass : function(cls){ 48 var clsName = " " + this.val.className + " "; 49 this.val.className = clsName.replace(new RegExp(" "+cls+ " ","g"),"").replace(/(^\s+)|(\s+$)/,""); 50 return this; 51 }, 52 addEvent : function(evType,fn){ 53 var that = this, typeEvent = this.val["on"+evType]; 54 if(!typeEvent){ 55 (this.val["on"+evType] = function(){ 56 var fnQueue = arguments.callee.funcs; 57 for(var i=0;i<fnQueue.length;i++){ 58 fnQueue[i].call(that.val); 59 } 60 }).funcs =[fn]; 61 }else{ 62 typeEvent.funcs.push(fn); 63 } 64 return this; 65 }, 66 delEvent : function(evType,fn){ 67 if(fn===undefined){ 68 this.val["on"+evType] = null; 69 }else{ 70 var fnQueue = this.val["on"+evType].funcs; 71 for(var i=fnQueue.length-1;i>-1;i--){ 72 if(fnQueue[i] === fn){ 73 fnQueue.splice(i,1); 74 break; 75 } 76 } 77 fnQueue.length==0 && (this.val["on"+evType] = null); 78 } 79 return this; 80 }, 81 unBox : function(){ 82 return this.val; 83 } 84 }; 85 //静态方法 86 var __ = D.dom; 87 __.$ = function(id){ 88 return typeof id == "string" ? document.getElementById(id) : id; 89 }; 90 __.$$ = function(tag,box){ 91 return (box===undefined?document:box).getElementsByTagName(tag); 92 }; 93 __.$cls = function(cls,tag,node){ 94 node = node === undefined ? document : node; 95 cls = cls.replace(/(\.)|(^\s+)|(\s+$)/g,""); 96 if(node.getElementsByClassName)return node.getElementsByClassName(cls); 97 tag = tag === undefined ? "*" : tag; 98 var filter = [], nodes = (tag==="*" && node.all) ? node.all : node.getElementsByTagName(tag); 99 for(var i=0,j=nodes.length;i<j;i++){ 100 nodes[i].nodeType==1 && ((" " + nodes[i].className + " ").indexOf(" "+cls+ " ")!=-1) && filter.push(nodes[i]); 101 } 102 return filter; 103 }; 104 //静态方法结束 105 alert(D.dom.$cls(".abc").length); 106 })();
Dom包装器的实例对象负责当前dom节点的自身操作。而"静态方法"部分则是提供了dom选择器的基本实现。 -----------------------------------华丽分割线---------------------------------------------------------------------------- 以上就是D类库的初级版本,其中的重要部分——对内置对象的扩展目前只有较少的方法扩展,比如对Number的扩展,在基于web的财务软件中,用到相当多的数字操作,其中有一些是常用处理,就可以将其添加入Number包装器,好处也是显而易见的。
最后如果你看到了这篇文章,也有足够的想法,我希望你能尽你所能来给于包装器更多的方法扩展,你的其中的一些主意可能会成为D成熟版本的一部分。 (责任编辑:admin) |