因為是輔助類庫,所以為了相容所有其他架構和類庫,採用了封裝器的方式對對象進行擴充。D類庫的最主要的內容是針對js常用內建對象的擴充,比如:String,Number,Array,Date等,這些擴充偏於具體的商務邏輯,比如對String擴充的trim方法、對Date擴充的toStr方法等,都是對一些常用但對象本身不支援且架構類庫也不支援或不完整支援的功能擴充。同時通過對應封裝器的封裝我們可以通過鏈式方法來操作對象,最後每個封裝器都提供了拆箱(即還原為原生對象)方法。故封裝器提供的實質是一個裝箱、操作、拆箱的過程。
命名空間: 複製代碼 代碼如下:var D = {};
部分功能如下:
. String封裝器 複製代碼 代碼如下:(function(){
//封裝String
D.str = function(s){
if(! (this instanceof y.str))return new y.str(s);
this.val = (s!==undefined) ? s.toString() : "";
};
D.str.prototype = {
//刪除字串兩邊空白
trim : function(type){
var types = {0:"(^\\s+)|(\\s+$)",1:"^\\s+",2:"\\s+$"};
type = type || 0;
this.val = this.val.replace(new RegExp(types[type],"g"),"");
return this;
},
//重複字串
repeat : function(n){
this.val = Array(n+1).join(this.val);
return this;
},
//字串兩邊補白
padding : function(len,dire,str){
if(this.val.length>=len)return this;
dire = dire || 0; //[0代表左邊,1代表右邊]
str = str || " "; //預設為一個空白字元
var adder = [];
for(var i=0,l = len - this.val.length; i<l;i++){
adder.push(str);
}
adder = adder.join("");
this.val = dire ? (this.val + adder) : (adder + this.val);
return this;
},
reverse : function(){
this.val = this.val.split("").reverse().join("");
return this;
},
byteLen : function(){
return this.val.replace(/[^\x00-\xff]/g,"--").length;
},
unBox : function(){
return this.val;
}
};
//alert(D.str(" 123 ").trim().repeat(2).padding(10,0,"x").reverse().unBox());
})();
.Array封裝器
複製代碼 代碼如下:(function(){
//封裝Array
D.arr = function(arr){
if(!(this instanceof D.arr))return new D.arr(arr);
this.val = arr || [];
};
D.arr.prototype = {
each : function(fn){
for(var i=0,len=this.val.length;i<len;i++){
if(fn.call(this.val[i])===false){
return this;
}
}
return this;
},
map : function(fn){
var copy = [];
for(var i=0,len = this.val.length;i<len;i++){
copy.push(fn.call(this.val[i]));
}
this.val = copy;
return this;
},
filter : function(fn){
var copy = [];
for(var i=0,len=this.val.length;i<len;i++){
fn.call(this.val[i]) && copy.push(this.val[i]);
}
this.val = copy;
return this;
},
remove : function(obj,fn){
fn = fn || function(m,n){
return m===n;
};
for(var i=0,len = this.val.length;i<len;i++){
if(fn.call(this.val[i],obj)===true){
this.val.splice(i,1);
}
}
return this;
},
unique : function(){
var o = {},arr = [];
for(var i=0,len = this.val.length;i<len;i++){
var itm = this.val[i];
(!o[itm] || (o[itm]!==itm) )&& (arr.push(itm),o[itm] = itm);
}
this.val = arr;
return this;
},
indexOf : function(obj,start){
var len = this.val.length,start = ~~start;
start < 0 && (start+= len);
for(;start<len;start++){
if(this.val[start]===obj)return start;
}
return -1;
},
lastIndexOf : function(obj,start){
var len = this.val.length,start = arguments.length === 2 ? ~~start : len-1;
start = start < 0 ? (start+len) : (start>=len?(len-1):start);
for(;start>-1;start--){
if(this.val[start] === obj)return start;
}
return -1;
},
unBox : function(){
return this.val;
}
};
//alert( D.arr(["123",123]).unique().unBox());
//alert(D.arr([1,2,3]).map(function(i){return ++i;}).filter(function(i){return i>2;}).remove(3).unBox());
})();
.Number封裝器 複製代碼 代碼如下:(function(){
//封裝Number
D.num = function(num){
if(!(this instanceof D.num))return new D.num(num);
this.val = Number(num) || 0;
};
D.num.prototype = {
padZore : function(len){
var val = this.val.toString();
if(val.length>=len)return this;
for(var i=0,l = len-val.length;i<l;i++){
val = "0" + val;
}
return val;
},
floatRound : function(n){
n = n || 0;
var temp = Math.pow(10,n);
this.val = Math.round(this.val * temp)/temp;
return this;
},
unBox : function(){
return this.val;
}
};
//alert(D.num(3.1235888).floatRound(3).unBox());
})();
.Date封裝器
複製代碼 代碼如下:(function(){
//封裝Date
D.date = function(date){
if(!(this instanceof D.date))return new D.date(date);
if(!(date instanceof Date)){
var d = new Date(date);
this.val = (d == "Invalid Date" || d == "NaN") ? new Date() : new Date(date);
}else{
this.val = date;
}
};
D.date.prototype = {
toStr : function(tpl){
var date = this.val,tpl = tpl || "yyyy-MM-dd hh:mm:ss";
var v = [date.getFullYear(),date.getMilliseconds(),date.getMonth()+1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()];
var k = "MM,M,dd,d,hh,h,mm,m,ss,s".split(",");
var kv = {"yyyy":v[0],"yy":v[0].toString().substring(2),"mmss":("000"+v[1]).slice(-4),"ms":v[1]};
for(var i=2;i<v.length;i++){
kv[k[(i-2)*2]] = ("0" + v[i]).slice(-2);
kv[k[(i-2)*2+1]] = v[i];
}
for(var k in kv){
tpl = tpl.replace(new RegExp( k,"g"),kv[k]);
}
return tpl;
},
unBox : function(){
return this.val;
}
};
//alert(D.date("2017-123-12").toStr("yyyy-MM-dd hh:mm:ss ms-mmss"));
// alert(D.date("2017").unBox());
})();
.最後為了在脫離其他架構類庫的情況下D也可以承擔dom操作方面的任務,實現了Dom封裝器,如下: 複製代碼 代碼如下:(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);
}else{
!node.getElementById && (node = document.body);
}
this.val = node;
};
D.dom.prototype = {
inner : function(value){
this.val.innerHTML ? (value = value || "",this.val.innerHTML = value) : (value = value || 0,this.val.value = value);
return this;
},
attr : function(k,v){
if(typeof k == "object"){
for(var m in k){
this.val[m] = k[m];
}
}else{
this.val[k] = v;
}
return this;
},
css : function(k,v){
var style = this.val.style;
if(typeof k == "object"){
for(var m in k){
style[m] = k[m];
}
}else{
style[k] = v;
}
return this;
},
addClass : function(cls){
var clsName = " " + this.val.className + " ";
(clsName.indexOf(" " + cls + " ")==-1) && (clsName = (clsName + cls).replace(/^\s+/,""));
this.val.className = clsName;
return this;
},
removeClass : function(cls){
var clsName = " " + this.val.className + " ";
this.val.className = clsName.replace(new RegExp(" "+cls+ " ","g"),"").replace(/(^\s+)|(\s+$)/,"");
return this;
},
addEvent : function(evType,fn){
var that = this, typeEvent = this.val["on"+evType];
if(!typeEvent){
(this.val["on"+evType] = function(){
var fnQueue = arguments.callee.funcs;
for(var i=0;i<fnQueue.length;i++){
fnQueue[i].call(that.val);
}
}).funcs =[fn];
}else{
typeEvent.funcs.push(fn);
}
return this;
},
delEvent : function(evType,fn){
if(fn===undefined){
this.val["on"+evType] = null;
}else{
var fnQueue = this.val["on"+evType].funcs;
for(var i=fnQueue.length-1;i>-1;i--){
if(fnQueue[i] === fn){
fnQueue.splice(i,1);
break;
}
}
fnQueue.length==0 && (this.val["on"+evType] = null);
}
return this;
},
unBox : function(){
return this.val;
}
};
//靜態方法
var __ = D.dom;
__.$ = function(id){
return typeof id == "string" ? document.getElementById(id) : id;
};
__.$$ = function(tag,box){
return (box===undefined?document:box).getElementsByTagName(tag);
};
__.$cls = function(cls,tag,node){
node = node === undefined ? document : node;
cls = cls.replace(/(\.)|(^\s+)|(\s+$)/g,"");
if(node.getElementsByClassName)return node.getElementsByClassName(cls);
tag = tag === undefined ? "*" : tag;
var filter = [], nodes = (tag==="*" && node.all) ? node.all : node.getElementsByTagName(tag);
for(var i=0,j=nodes.length;i<j;i++){
nodes[i].nodeType==1 && ((" " + nodes[i].className + " ").indexOf(" "+cls+ " ")!=-1) && filter.push(nodes[i]);
}
return filter;
};
//靜態方法結束
alert(D.dom.$cls(".abc").length);
})();
Dom封裝器的執行個體對象負責當前dom節點的自身操作。而"靜態方法"部分則是提供了dom選取器的基本實現。
以上就是D類庫的初級版本,其中的重要部分——對內建對象的擴充目前只有較少的方法擴充,比如對Number的擴充,在基於web的財務軟體中,用到相當多的數字操作,其中有一些是常用處理,就可以將其添加入Number封裝器,好處也是顯而易見的。
最後如果你看到了這篇文章,也有足夠的想法,我希望你能盡你所能來給於封裝器更多的方法擴充,你的其中的一些主意可能會成為D成熟版本的一部分。