Home >Web Front-end >JS Tutorial >JavaScript library D_javascript skills

JavaScript library D_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:17:531011browse

Because it is an auxiliary class library, in order to be compatible with all other frameworks and class libraries, a wrapper is used to extend the object. The main content of the D class library is the extension of commonly used built-in objects in js, such as: String, Number, Array, Date, etc. These extensions focus on specific business logic, such as the trim method extended to String and toStr extended to Date. Methods, etc. are extensions to some commonly used functions that are not supported by the object itself and are not supported or incompletely supported by the framework class library. At the same time, through the packaging of the corresponding wrapper, we can operate the object through the chain method. Finally, each wrapper provides an unboxing (that is, restoring to the native object) method. Therefore, the essence provided by the packager is a process of packing, operating, and unpacking.

namespace:

Copy code The code is as follows:

var D = {};

Some functions are as follows:

. String wrapper
Copy code The code is as follows:

(function(){
//Packaging String
D.str = function(s){
if(! (this instanceof y.str ))return new y.str(s);
this.val = (s!==undefined) ? s.toString() : "";
};
D.str.prototype = {
//Remove the blanks on both sides of the string
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 string
repeat: function(n){
this.val = Array(n 1).join(this.val);
return this;
},
//Padding on both sides of the string
padding: function(len,dire,str){
if(this.val.length>=len)return this;
dire = dire || 0; //[0 represents the left, 1 represents the right]
str = str || " "; //The default is a blank character
var adder = [];
for(var i=0,l = len - this.val.length; iadder.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 wrapper

Copy code Code As follows:

(function(){
//Packaging 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;iif(fn.call(this.val[i])===false){
return this;
}
}
return this;
},
map : function(fn){
var copy = [];
for(var i=0,len = this .val.length;icopy.push(fn.call(this.val[i]));
}
this.val = copy;
return this ;
},
filter : function(fn){
var copy = [];
for(var i=0,len=this.val.length;ifn.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;iif(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;ivar 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 wrapper
Copy code The code is as follows:

(function(){
//Pack 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;ival = "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 packaging Device

Copy code The code is as follows:

(function(){
//Packaging 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;ikv[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());
})();


. Finally, in order for D to be able to undertake the task of dom operation without being separated from other framework libraries, a Dom wrapper was implemented, as follows:
Copy code The code is as follows:

(function(){
2 //包装Dom
3 D.dom = function(node){
4 if(!(D.dom의 이 인스턴스))return new D .dom(노드);
5 if(typeof 노드 === "정의되지 않음"){
6 node = document.body
7 }else if(typeof 노드 == "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 ? || "",this.val.innerHTML = 값) : (값 = 값 || 0,this.val.value = 값)
return this
},
attr : function(k ,v){
if(typeof k == "객체"){
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. 클래스명 " ";
(clsName.indexOf(" " cls " ")==-1) && (clsName = (clsName cls).replace(/^s /,""));
this.val.className = clsName;
이것을 돌려주세요;
},
removeClass : function(cls){
var clsName = " " this.val.className " ";
this.val.className = clsName.replace(new RegExp(" " cls " ","g"),"").replace(/(^s )|(s $)/,"");
이것을 돌려주세요;
},
addEvent : function(evType,fn){
var that = this, typeEvent = this.val["on" evType];
if(!typeEvent){
(this.val["on" evType] = function(){
var fnQueue = 인수.callee.funcs;
for(var i=0;i< ;fnQueue.length;i ){
fnQueue[i].call(that.val)
}
}).funcs =[fn];
}else{
typeEvent.funcs.push(fn);
}
이것을 반환하세요.
},
delEvent : function(evType,fn){
if(fn===undefine){
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) ;
휴식;
}
}
fnQueue.length==0 && (this.val["on" evType] = null);
}
이것을 반환하세요.
},
unBox : function(){
return this.val;
}
};
//静态방법
var __ = D.dom;
__.$ = function(id){
반환 유형 id == "string" ? document.getElementById(id) : id;
};
__.$$ = function(tag,box){
return (box===undefine?document:box).getElementsByTagName(tag);
};
__.$cls = function(cls,tag,node){
node = node === 정의되지 않음 ? 문서: 노드;
cls = cls.replace(/(.)|(^s )|(s $)/g,"");
if(node.getElementsByClassName)return node.getElementsByClassName(cls);
태그 = 태그 === 정의되지 않음 ? "*" : 태그;
var filter = [], 노드 = (tag==="*" && node.all) ? node.all : node.getElementsByTagName(태그);
for(var i=0,j=nodes.length;inodes[i].nodeType==1 && ((" " 노드[i].className " "). indexOf(" " cls " ")!=-1) && filter.push(nodes[i]);
}
반환 필터;
};
//静态方法结束
alert(D.dom.$cls(".abc").length);
})();


Dom包装器的实例对象负责当前dom节点的自身操작품 🎜>
以上就是D类库的初级版本, 其中的要要part——对内置对象的扩展目前只有较少象的物話,比如对Numberally 扩件中,到当多数字操작품,其中有一些是常可以将其添加入Number包装器,好处也是显而易见的。

最后如果你看到了这篇文章,有足够的想法,我希望你能尽你所能来给于包装더 많은 방법을 확장하면, 이 부분이 주요 의미로 사용됩니다.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn