打造自己的js库

随着code经验的增加,函数封装,可复用性组件开发可以说是一个水到渠成的过程,最近一直想写一个属于自己的js库,将自己用的较多的组件都放在里面,但是也一直被搁置,因为我感觉自己目前能力可能不够,但是不试试怎么知道呢。只要尝试,就算不成功,对自己也是宝贵的经验。

万事开头难,这一步很关键,使用命名空间避免冲突,将方法绑定到window上。ps:能有今天的成长,大部分归功于前辈们的代码通过解读能学到很多东西,感谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace = function(){
var args = arguments; //函数内部args为参数长度
for(var i = 0;i<args.length;i++){ //循环截取参数绑定到window上边
var objs = args[i].split('.');
var obj = window;
for(var j = 0;j<objs.length;j++){
obj[objs[j]] = obj[objs[j]] || {};
obj = obj[objs[j]]
}
}
return obj
}
namespace("gu.base")//启动方式

运行完成后,window上边会绑定gu,gu下边有方法base,然后在gu.base上边进行函数扩展。

  • base
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
namespace('gu.base');

(function () {
/**
* 获取传入参数类型
* @param {object} obj
* @return {string}
* @date 2017-11-16
*/
function getParamType (obj) {
return (obj == null ? String(obj) : Object.prototype.toString.call(obj).replace(/\[object\s+(\w+)\]/i,"$1") || "object").toLowerCase();
};

/**
* 类似$.extend()
* @param destination
* @param source
* @return {object} destination
* @date 2017-11-16
*/
gu.base.extend = function (destination,source) {
if (destination == null) {
destination = source
}
else {
for (var property in source){
if (getParamType(source[property]).toLowerCase() === "object" &&
getParamType(destination[property]).toLowerCase() === "object" )
arguments.callee(destination[property], source[property])
else
destination[property] = source[property];
}
}
return destination;
};

gu.base.isArray = function (obj) {
return getParamType(obj) === "array";
};

gu.base.isObject = function (obj) {
return getParamType(obj) === "object";
};

gu.base.isFunction = function (obj) {
return getParamType(obj) === "function";
};

gu.base.isString = function (obj) {
return getParamType(obj) === "string";
};

gu.base.isBoolean = function (obj) {
return getParamType(obj) === "boolean";
};

gu.base.isDate = function (obj) {
return getParamType(obj) === "date"
};
gu.base.g = function (id) {
return document.getElementById(id);
}

})();
gu.base.extend(window, gu.base);
  • date
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace('gu.date');

extend(gu.date,{
/**
*获取日期,默认日期为今天,默认分隔符为'-'
* @param time
* @returns {string}
* @date 2017-11-21
*/
toDateString:function (time) {
var time = time ? time : new Date(),
m = time.getMonth(),
d = time.getDay(),
y = time.getFullYear(),
separator = arguments[1] ? arguments[1] : '-';

return y + separator + (m.toString().length < 2 ? '0' + m : m) +separator +(d.toString().length < 2 ? '0' + d : d);
},
/**
* 获取日期以及时间,默认日期为今天,默认分隔符为'-'
* @param time
* @returns {string}
* @date 2017-11-21
*/
toDateTimeString:function (time) {
var time = time ? time : new Date(),
h = time.getHours(),
i = time.getMinutes(),
s = time.getSeconds();

return gu.date.toDateString.apply(this,arguments) + " " + (h.toString().length < 2 ? '0' + h : h)+ ":" + (i.toString().length < 2 ? '0' + i : i)+ ":" + (s.toString().length < 2 ? '0' + s : s);
}
});
  • load
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace('gu.load');

extend(gu.load,{
/**
* 加载js
* @param url
* @param callback
* @returns {boolean}
* @date 2017-11-21
*/
loadScript:function (url, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.charset = 'GBK';
script.src = url;
var timeout = setTimeout(
function (){
head.removeChild(script);
callback.call(this,false);
},
50
);

script.onload = function () {
head.removeChild(script);
clearTimeout(timeout);
callback();
};
head.appendChild(script);
return true;
},
/**
* 加载css
* @param url
* @param callback
* @date 2017-11-21
*/
loadCss:function (url, callback) {
var head = document.getElementsByTagName("head")[0];
var link = head.appendChild(
document.createElement("link")
);
link.href = url;
link.rel = 'stylesheet';
callback.call(this,true);
}
});

extend(window,gu.load);
  • cookie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
namespace('gu.cookie');

extend(gu.cookie,{
/**
* 设置cookie,最好先用navigator.cookieEnable判断一下cookie是否可用
* @param key
* @param value
* @param expires
* @param domain
* @param path
* @returns {boolean}
*/
set:function (key,value,expires,domain,path) {
var cValue,cExpires,cDomain,cPath,cookieArr = [];
if(!key){
return false;
}
cValue = value ? encodeURIComponent(value) : '';
cookieArr.push(key + "=" + cValue);
if(!isNaN(expires)){
var time = new Date();
time.setTime(time.getTime()+(expires*24*60*60*1000));
cExpires = time.toGMTString();
cookieArr.push('expires=' + cExpires);
}
if(domain != undefined){
cDomain = domain;
cookieArr.push('domain=' + cDomain);
}
if(path != undefined){
cPath = path;
cookieArr.push('path=' + cPath);
}
document.cookie = cookieArr.join('; ');
},
/**
* 获取cookie
* @param key
* @returns {string}
*/
get:function (key) {
var cookieArr = document.cookie.split('; ');
for(var i=0;i<cookieArr.length;i++){
if(cookieArr[i].indexOf(key) == 0){
return decodeURIComponent(cookieArr[i].substring(cookieArr[i].split('=')[0].length + 1,cookieArr[i].length));
}
}
},
/**
* 清除cookie
* @param key
* @param domain
*/
clear:function (key,domain) {
var cDate = new Date();
gu.cookie.set(key,"",-2,domain);
}
});
  • string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace('gu.string');
extend(gu.string,{
/**
* 获得字节数,中文2
* @param str
* @returns {number}
*/
getByteLength:function (str) {
var bytes = 0;
for(var i=0;i<str.length;i++){
if(str.charCodeAt(i) > 255){
bytes ++
}
bytes ++
}
return bytes;
},
/**
* 去空
* 数据库中utf-8占三个字符,gbk占俩
* @param str
* @returns {XML|string|*}
*/
trim:function (str) {
str = str.replace(/\s+$/,'').replace(/^\s+/,'');
return str;
}
});
  • config
1
2
3
4
namespace('gu.config');
extend(gu.config,{
host:'//111.231.54.181'
});
  • ajax通用部分封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function ($) {
$.ajaxSetup({
dataType:'json',
beforeSend:function (xhr) {
xhr.withCredentials = true;
commTool.loadingOpen();
},
complete:function () {
commTool.loadingClose();
},
error:function () {
commTool.msg('网络无法连接,请稍后再试。');
}
});
})(jQuery);